首页 > 编程语言 > 详细

ES5的数组方法

时间:2017-11-29 15:48:29      阅读:295      评论:0      收藏:0      [点我收藏+]

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Array.prototype.forEach()

[1, 2, 3, 4, 5].forEach(function(item, index, array) {  
    console.log(‘the current index is: ‘ + index + ‘, value is: ‘ + item);  
});  

Array.prototype.filter()

过滤所有偶数,返回true,则该元素会被保留下来

var oddArr = [1, 2, 3, 4, 5].filter(function(item) {  
    return item % 2 !== 0;  
});

 配合indexOf实现数组去重:

var arr = [1,1,2,3,5,5,2,9,0,0].filter((item,index,arr)=>{
    return arr.indexOf(item) === index;
});

ES6 使用Set实现数组去重:

var arr = [...new Set([1,1,2,3,5,5,2,9,0,0])];

Array.prototype.map()

var doubleArr = [1, 2, 3, 4, 5].map(function(item) {  
    return item * 2;  
});

Array.prototype.some()

只要存在大于3的元素,则some返回true

var someoneGreaterThan3 = [1, 2, 3, 4, 5].some(function(item) {  
    return item > 3;  
}); 

与some对应的还有一个every方法,这个方法要求所有元素都满足条件,也就是闭包中都返回true时,every才会返回true

 

ES5的数组方法

原文:http://www.cnblogs.com/hellohello/p/7920566.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!