1、some()
some()方法用于检测数组中的元素是否满足指定条件。
some() 方法会一次执行数组的每个元素:
- 如果有一个元素满足条件,则返回true,剩余元素不会再执行检测。
- 如果没有满足条件的元素,则返回false。
语法:
var bool = array.some(function(currentValue,index,arr),thisValue);
参数:
参数 | 是否必须 | 描述 |
---|---|---|
function(currentValue,index,arr) | 必须 | 函数,数组中的每个元素都会执行这个函数 |
thisValue | 可选 | 对象作为该执行回调时使用,传递给函数,用作 “this” 的值。如果省略了 thisValue ,“this” 的值为 “undefined” |
var arr = [ 1, 2, 3, 4, 5, 6 ];
var result = arr.some( function( item, index, array ){
console.log( 'item=' + item + ',index='+index+',array='+array );
return item > 3;
});
//item=1,index=0,array=1,2,3,4,5,6
//item=2,index=1,array=1,2,3,4,5,6
//item=3,index=2,array=1,2,3,4,5,6
//item=4,index=3,array=1,2,3,4,5,6
result
//true
注意: some() 不会对空数组进行检测,也不会改变原始数组。
2、every()
every()方法用于检测数组中的元素是否满足指定条件。
every() 方法使用指定函数检测数组中的所有元素:
- 如果数组中有一个元素不满足,则返回false,且剩余元素不会再进行检测。
- 如果所有元素都满足条件,则返回true。
语法:
var bool = array.every(function(currentValue,index,arr), thisValue)
例子:
var arr = [ 1, 2, 3, 4, 5, 6 ];
var every = arr.every( function( item, index, array ){
console.log( 'item=' + item + ',index='+index+',array='+array );
return item > 3;
});
//item=1,index=0,array=1,2,3,4,5,6
every;
//false
注意: every() 不会对空数组进行检测,也不会改变原始数组。
3、filter()
filter()方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
语法:
var newArr = array.filter(function(currentValue,index,arr), thisValue)
例子:
var arr = [32,15,12,16,18,115,1];
var newArr = arr.filter(function(cur){return cur > 25});
newArr;//[32, 115]
arr;//[32,15,12,16,18,115,1]
如果没有符合条件的元素则返回空数组。
注意: filter() 不会对空数组进行检测,也不会改变原始数组。
4、map()
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
var newArr = array.map(function(currentValue,index,arr), thisValue);
例子:
var arr = [ 1, 2, 3, 4, 5, 6 ];
var result = arr.map( function( item, index, array ){
return item * item;
});
result;//[1, 4, 9, 16, 25, 36]
arr;//[ 1, 2, 3, 4, 5, 6 ]
map()与filter()函数的主要区别是,map()返回的数组长度肯定跟原数组相等,filter()函数返回的数组长度不一定跟原数组相等。
注意: map() 不会对空数组进行检测,也不会改变原始数组。
4、forEach()
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
array.forEach(function(currentValue, index, arr), thisValue)
forEach() 为每个数组元素执行callback函数;不像 map() 或者 reduce(),它总是返回 undefined 值,并且不可链式调用。
例子:
const items = ['item1', 'item2', 'item3'];
const copy = [];
items.forEach(function(item){
copy.push(item);
});
copy;//["item1", "item2", "item3"]
注意: forEach() 对于空数组是不会执行回调函数的。