JS 数组遍历的方法

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
var a = [1,2,3,4,5,6];
var b = a.some(function(ele,index,arr){
    console.log(ele);//输出1,2,3遍历到3停止遍历
    return ele > 2;   
});
console.log(b);
console.log("--------------------");
var c = a.every(function(ele,index,arr){
    console.log(ele);//输出1,2,3,4,5遍历到5返回false,停止遍历
    return ele < 5;
});
console.log(c);
console.log("--------------------");
var d = a.filter(function(ele,index,arr){
    console.log(ele);//遍历整个数组,将值大于3的项添加到d数组中
    return ele > 3;   
});
console.log(d);
console.log("--------------------");
var e = a.map(function(ele,index,arr){
  	console.log(ele);//遍历整个数组,对数组的每个元素执行一次操作,将新的元素添加到e数组中
    return ele+3;
});
console.log(e);
console.log("--------------------");
a.forEach(function(ele,index,arr){
    arr[index] = ele+6;//遍历数组,对数组中的每项执行一次操作,无返回值
});
console.log(a);
</script>
</body>
</html>

  

some:只要数组中有满足条件的选项,就返回true,不再遍历剩余元素,如果所有项都没有满足条件,则返回false
every:只要数组中有不满足条件的选项,就返回false,不再遍历剩余元素,如果所有项都满足条件,则返回true
filter:筛选数组,该函数返回新的数组,将原数组中满足条件的元素push到新数组中
map:对数组中的每个元素都执行一次callback函数,并返回新的元素到新数组中
forEach:对数组中的每个元素执行一次callback函数,该函数没有返回值

效果图:

 
 

猜你喜欢

转载自onestopweb.iteye.com/blog/2323726