您的位置:首页 > Web前端 > JavaScript

es5中js的数组 新增方法总结

2016-10-24 17:13 387 查看
es5中给js的数组增添了许多实用的方法,利用这些方法可以帮助我们更加快速方便的写js代码,然后蛋疼的是低版本ie肯定是不支持的,所以..................自己动手丰衣足食。让我们一步步看下如何使用与实现这些方法。

forEach

map

filter

some

every

indexOf

lastIndexOf

reduce

reduceRight


forEach

这个方法作用是啥咧,就是循环,遍历。比如一般我们在for循环做这样的事的时候如下。
var arr = [1, 2, 3, 4, 5, 6];

for (var i = 0, len = arr.length; i < len; i++) {
console.log(arr[i], i, arr);
}


如果用forEach我们应该如何做呢?

var arr = [1, 2, 3, 4, 5, 6];

arr.forEach(function (e, i, array) {
console.log(e, i, array)
})


是不是觉得不用写for循环了,瞬间逼格都高了

forEach函数中的回调函数支持三个参数, 
1、数组的值
 , 
2、值的索引
 , 
3、数组本身
 。这样的调用方式是不是和jQuery中的$.each很像?
其实不然,jQuery和forEach回调函数的第一个和第二个参数正好是反着来的。


看看对比

var arr = [1, 2, 3, 4, 5];

// forEach
arr.forEach(function (e, i, array) {
console.log(e, i, array);
})

// output

1 0 [1, 2, 3, 4, 5]
2 1 [1, 2, 3, 4, 5]
3 2 [1, 2, 3, 4, 5]
4 3 [1, 2, 3, 4, 5]
5 4 [1, 2, 3, 4, 5]

// $.each
$.each(arr, function (i, e, array) { // 测试的时候发现array是undefined,查了文档也发现没有第三个参数
console.log(i, e, array);
})

// output

0 1 undefined
1 2 undefined
2 3 undefined
3 4 undefined
4 5 undefined


接着我们来看一下forEach的第二个参数,这个参数决定第一个回调函数的内部this指向

var arr = [1, 2, 3, 4, 5];

//  默认情况下,第二个参数不传入时
arr.forEach(function (e, i, array) {
console.log(e, i, array, this);
})

// output
1 0 [1, 2, 3, 4, 5] window
2 1 [1, 2, 3, 4, 5] window
3 2 [1, 2, 3, 4, 5] window
4 3 [1, 2, 3, 4, 5] window
5 4 [1, 2, 3, 4, 5] window

// 传入参数
arr.forEach(function (e, i, array) {
console.log(e, i, array, this);
}, {name: 'qianlong'})

// output
1 0 [1, 2, 3, 4, 5] {name: 'qianlong'}
2 1 [1, 2, 3, 4, 5] {name: 'qianlong'}
3 2 [1, 2, 3, 4, 5] {name: 'qianlong'}
4 3 [1, 2, 3, 4, 5] {name: 'qianlong'}
5 4 [1, 2, 3, 4, 5] {name: 'qianlong'}


最后接下来我们自己实现一下这个方法

var ObjPro = Object.prototype,
hasOwn = ObjPro.hasOwnProperty,
nativeArray = ObjPro.forEach;

Array.prototype.forEach = nativeArray || function (callBack, ctx) {
if (typeof callBack != 'function') return;

for (var i =0, len = this.length; i < len; i++) {
if (hasOwn.call(this, i)) {
callBack.call(ctx, this[i], i, this);
}
}
}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: