数组的迭代方法

forEach
作用:循环遍历数组每一项
参数:函数 ary.forEach(function(item,index,ary){}) item:每一项 index:索引 ary:当前数组
返回值:无
是否改变原数组: 不改变

var ary = ['a','b','c']
var res = ary.forEach(function (item,index,ary) {
    console.log (item,index,ary);
/*  a 0 ["a", "b", "c"]
    b 1 ["a", "b", "c"]
    c 2 ["a", "b", "c"]
*/  
    return item;
})
console.log (res)  // undefined  无返回值

map
作用:数组中的元素为原始数组元素调用函数处理后的值
参数:函数 ary.map(function(item,index,ary){}) item:每一项 index:索引 ary:当前数组
返回值:新数组
是否改变原数组:不改变

var ary = ['a','b','c']
var res = ary.map (function (item,index,ary) {
    return item+1;
})
console.log (res)  // ["a1", "b1", "c1"]

filter
作用:创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
参数:函数 ary.filter(function(item,index,ary){}) item:每一项 index:索引 ary:当前数组
返回值:新数组
是否改变原数组:不改变

var ary = [1,2,3,4,5,6]
var res = ary.filter (function(item) {
    return item<3;
})
 console.log (res)  // [1,2]

every
作用:检测数组所有元素是否都符合指定条件,
参数:函数 ary.every(function(item,index,ary){}) item:每一项 index:索引 ary:当前数组
返回值:布尔值
是否改变原数组: 不改变

var ary = [1,2,3,4,5,6]
var res = ary.every (function(item) {
    return item<3;
})
 var res2 = ary.every (function(item) {
    return item<7;
})
 console.log(res)  // false;
console.log(res2) // true;
// 1 如果数组中检测到有一个元素不满足,则整个表达式返回 false 。且剩余的元素不会再进行检测。
// 2 如果所有元素都满足条件,则返回 true。

some
作用:检测数组中的元素是否满足指定条件
参数:函数 ary.some(function(item,index,ary){}) item:每一项 index:索引 ary:当前数组
返回值:布尔值
是否改变原数组:不改变

var ary = [1,2,3,4,5,6]
var res = ary.some (function(item) {
    return item<3;
})
 console.log(res)  // true;
// 1 如果有一个元素满足条件,则表达式返回 true 。剩余的元素不会再执行检测。
// 2 如果没有满足条件的元素,则返回 false。

你可能感兴趣的:(数组的迭代方法)