盘点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 值。
相关文章
相关标签/搜索