美文网首页
常见数组操作方法(容易混乱)

常见数组操作方法(容易混乱)

作者: windyoung1990 | 来源:发表于2018-03-02 20:36 被阅读0次
var arr = [1,2,3,4,5];
//forEach
arr.forEach(function(item, index){
    console.log(item, index);//item 数组每一项内容, index 每一项的索引
});
arr.map(function(item, index, arr){
    return item * item;//map方法不会改变原数组,对原始数组调用函数处理后,返回一个新数组[1,4,9,16,25];
});
arr.reduce(function(total, currentValue, index, arr){
    return total + currentValue;// 15  total 作为累加器,最开始默认为数组第一个值
});

filter方法巧妙实现数组去重

var arr = ['apple', 'banana', 'apple'];
arr.filter(function(item, index, arr){
    return arr.indexOf(item) === index;
});

相关文章

网友评论

      本文标题:常见数组操作方法(容易混乱)

      本文链接:https://www.haomeiwen.com/subject/zuhzxftx.html