1.forEach
forEach遍历数组,里面包含了一个匿名函数,匿名函数里面有三个参数,第一个参数为item为元素的值,第二个为index,元素的索引号,第三个为arr,原数组,我们只需要根据自己所需要的去写即可
var arr = [1,2,3,4,5,6]
function testForeach(){
arr.forEach(function(item,index,arr){
console.log('元素的值为:',item,'元素的索引号为:',index,'打印原数组:',arr);
})
}
testForeach();
2.map
map,与forEach相似,都是遍历数组,不过map可以对数组里的每一项进行操作,并且返回一个新的数组。
function testMap(){
var newArr = arr.map(function(item,index){
return item-10;
})
console.log('map改变的数值:',newArr);
}
testMap();
3.filter
filter是一个过滤,相当于根据你设置的条件来过滤数组
function testFilter(){
var newArr = arr.filter(function(item,index){
return index==1;
})
console.log('返回索引号为1的值:',newArr);
}
testFilter();
4.find
find也是查找数组中的满足条件的元素,不过他只会找到第一个满足条件的就会返回给新的数组
function testFind(){
var newArr = arr.find(function(item,index){
return item>2;
})
console.log('find查找的',newArr);
}
testFind();
5.every
every也是查找符合条件的数组,不过every的要求是数组中全部满足条件就返回true,只要有一个不满足就返回false
function testEvery(){
var isOk = arr.every(function(item,index){
return item>2;
})
console.log('every的值:',isOk);
}
testEvery();
6.some
some和every类似,不过some是只要有其中一个满足条件就返回true