js 迭代方法

迭代方法

* every():对数组中的每一项运行给定函数,如果该函数对每一项都返回true,则返回true。
* filter():对数组中的每一项运行给定函数,返回该函数会返回true 的项组成的数组。
* forEach():对数组中的每一项运行给定函数。这个方法没有返回值。
* map():对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组。
* some():对数组中的每一项运行给定函数,如果该函数对任一项返回true,则返回true。

arr.every(function(item,index,arr){ })
//对应的元素,对应的下标,操作的数组,相当于所有元素在函数内部操作的结果相与的值,some相当于或的值
每个方法都没有改变原来数组的值那类似于forEach有什么应用呢

// 迭代方法every
var everyRst = a.every(function(item,index){
    if(item>1){ //若此处为>=1,则下面返回true
        return true;
    }
})
cons(everyRst); //false

// 迭代方法some
var someRst = a.some(function(item,index,arr){
    if(item>6){ //若此处为>=1,则下面返回true
        return true;
    }
// cons(index);
// cons(arr); //对应的传入的数组
})
// 迭代方法forEach
var cc = [];
a.forEach(function(item,index,arr){
    item = item +2;
    cc[index] = item;
})
// 迭代方法map
var dd = a.map(function(item,index,arr){
    return item = item +2; //返回值必须自己设置么?return
    // 当为 item = item +2; 打印的所有的dd都是undefined
})
cons(a); //(11) [1, 2, 3, 4, 5, 6, 4, 5, 6, 4, 7]
cons(cc);//(11) [3, 4, 5, 6, 7, 8, 6, 7, 8, 6, 9]
cons(dd);//(11) [3, 4, 5, 6, 7, 8, 6, 7, 8, 6, 9]
cons(someRst); //true
function cons(t){
    console.log(t);
}    



原文地址:https://www.cnblogs.com/xhliang/p/9107716.html