盤點JavaScript裏好用的原生API ꒰・◡・๑꒱

這段時間翻了一番JavaScript的api,發現很多好的輪子,省去造的麻煩了。segmentfault

直接進入正題api

解析字符串對象

咱們都知道,JavaScript對象能夠序列化爲JSON,JSON也能夠解析成對象,可是問題是若是出現了一個既不是JSON也不是對象的"東西",轉成哪一方都不方便,那麼eval就能夠派上用場

var obj = "{a:1,b:2}";   // 看起來像對象的字符串
eval("("+ obj +")")      // {a: 1, b: 2}

由於 eval 能夠執行字符串表達式,咱們但願將 obj 這個字符串對象 執行成真正的對象,那麼就須要用eval。可是爲了不eval 將帶 {} 的 obj 當語句來執行,咱們就在obj的外面套了對 (),讓其被解析成表達式。數組

& (按位與)

判斷一個數是否爲2的n次冪,能夠將其與自身減一相與

var number = 4
(number & number -1) === 0 // true

^ (按位異或)

不用第三個變量,就能夠交換兩個變量的值
var a = 4,b = 3
a = a ^ b  //    7
b = a ^ b  //    4
a = a ^ b  //    3

格式化Date

想獲得format後的時間?如今不用再get年月日時分秒了,三步搞定

var temp = new Date();
var regex = /\//g;
(temp.toLocaleDateString() + ' ' + temp.toLocaleTimeString().slice(2)).replace(regex,'-');

// "2015-5-7 9:04:10"

想將format後的時間轉換爲時間對象?直接用Date的構造函數

new Date("2015-5-7 9:04:10");

// Thu May 07 2015 09:04:10 GMT+0800 (CST)
經測試發現火狐無法對format後的時間字符串使用Date.parse(),故這個方法在火狐上很差使

想將一個標準的時間對象轉換爲unix時間戳?valueOf搞定之

(new Date).valueOf();

// 1431004132641

許多朋友還提醒了這樣能夠快速獲得時間戳

+new Date
// 1431004132641

一元加

一元加能夠快速將字符串的數字轉換爲數學數字,即
var number = "23" 
typeof number  // string
typeof +number // number

能夠將時間對象轉爲時間戳
new Date  //  Tue May 12 2015 22:21:33 GMT+0800 (CST)
+new Date //  1431440459887

轉義URI

須要將url當作參數在路由中傳遞,如今轉義之

var url = encodeURIComponent('http://segmentfault.com/questions/newest')

// "http%3A%2F%2Fsegmentfault.com%2Fquestions%2Fnewest"

再反轉義

decodeURIComponent(url)
// "http://segmentfault.com/questions/newest"

Number

但願保留小數點後的幾位小數,不用再作字符串截取了,toFixed拿走
number.toFixed()     // "12346"
number.toFixed(3)    // "12345.679"
number.toFixed(6)    // "12345.678900"

參數範圍爲0~20,不寫默認0

類型檢測

typeof是使用最頻繁的類型檢測手段

typeof 3        // "number"
typeof "333"    // "string"
typeof false    // "boolean"

對於基本(簡單)數據類型仍是挺好的,可是一旦到了引用數據類型的時候,就不那麼好使了

typeof new Date()   // "object"
typeof []           // "object"
typeof {}           // "object"
typeof null         // "object"      

前三個還能忍,null竟然也返回object,你是在逗我嗎!!!(ps:其實這是JavaScript的bug 人艱不拆 ꒰・◡・๑꒱ )

這時,咱們會使用instanceof

toString instanceof Function
// true
(new Date) instanceof Date
// true
[] instanceof Object
// true
[] instanceof Array
// true

其實咱們能夠發現,[] 和 Object獲得了true,雖然咱們知道,[]也是對象,可是咱們但願一個能更準確的判斷類型的方法,如今它來了

使用Object.prototype.toString()來判斷,爲了讓每個對象都能經過檢測,咱們須要使用Function.prototype.call或者Function.prototype.apply的形式來調用

var toString = Object.prototype.toString;

toString.call(new Date)    // "[object Date]"
toString.call(new Array)   // "[object Array]"
toString.call(new Object)  // "[object Object]"
toString.call(new Number)  // "[object Number]"
toString.call(new String)  // "[object String]"
toString.call(new Boolean) // "[object Boolean]"

要注意的是:toString方法極有可能被重寫,因此須要使用的時候,
能夠直接使用Object.prototype.toString()方法

實現繼承

看一個官方給的例子
//Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

Shape.prototype.move = function(x, y) {
    this.x += x;
    this.y += y;
    console.info("Shape moved.");
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); //call super constructor.
}

Rectangle.prototype = Object.create(Shape.prototype);

var rect = new Rectangle();

rect instanceof Rectangle //true.
rect instanceof Shape //true.

rect.move(1, 1); //Outputs, "Shape moved."

經過call來獲取初始化的屬性和方法,經過Object.create來獲取原型對象上的屬性和方法

迭代

ES5出了挺多的迭代函數,如map,filter,some,every,reduce等,這裏有傳送門,能夠看到挺多的例子

http://segmentfault.com/a/1190000002687651app

Array

具體的api這裏介紹的很詳細。

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Glob...函數

這裏就提幾句:
pop,push,reverse,shift,sort,splice,unshift會改變原數組

join,concat,indexOf,lastIndexOf,slice,toString不會改變原數組

map,filter,some,every,reduce,forEach這些迭代方法不會改變原數組

幾個注意點:

1 shift,pop會返回那個被刪除的元素
2 splice 會返回被刪除元素組成的數組,或者爲空數組
3 push 會返回新數組長度
4 some 在有true的時候中止
5 every 在有false的時候中止
6 上述的迭代方法能夠在最後追加一個參數thisArg,它是執行 callback 時的 this 值。
相關文章
相關標籤/搜索