数组遍历filter,forEach,map,every,some,reduce

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_39921345/article/details/78786112
filter:筛选出符合数组的项,返回新数组。功能和map类似;
map:map是通过某种计算返回新数组。实际应用中,用map方法方便获得对象数组中的特定属性。
forEach:es5新增的方法,等同于传统的for循环。forEach方法中的function回调支持3个参数,第1个是遍历的数组内容,第2个是对应的数组索引,第3个是数组本身:[].forEach(function(value,index,array){});与Jquery中的$.each的区别是第一个参数和第二个参数的位置不同:(index,value,array)。
reduce:让数组中的前项和后项进行某种计算,并累计最终值。实际中,方便实现二维数组的扁平化。
some: 检测数组中某些值是否符合条件。返回true就不在执行。
every:检测数组中每项是否符合条件。

1.filter:

<body>
<ul>
<li>
<ahref="#">sdffsdf</a>
</li>
</ul>
<script>
// filter:指数组filter后,返回过滤后的新数组。用法跟map相似:
// array.filter(callback,[ thisObject]);

vardata =[0,1,2,3];
vararrayFilter = data.filter(function(item) {
returnitem;
});
console.log(arrayFilter);// [1, 2, 3]
</script>
</body>

2.forEach:
< script >
// forEach是Array新方法中最基本的一个
[1,2,3,4].forEach(console.log);
//等同于下面这个传统的for循环:
vararray =[1,2,3,4];
for(vark =0;k < array.length;k++) {
console.log(array[k]);
}
// Array在ES5新增的方法中,参数都是function类型,默认有传参
// forEach方法中的function回调支持3个参数,第1个是遍历的数组内容;第2个是对应的数组索引,第3个是数组本身。
[1,2,3,4].forEach(console.log);

//所以就有:
// [].forEach(function(value, index, array) {
// // ...
// });
// //对比jQuery中的$.each方法:
// $.each([], function(index, value, array) {
// // ...
// });
//注意:两个方法第1个和第2个参数正好是相反的。

//举个例子:数组求和
varsum =0;

[1,2,3,4].forEach(function(item,index,array) {
console.log(array[index]==item);// true
sum +=item;
});

console.log(sum);// 10

//forEach除了接受一个必须的回调函数参数,
//还可以接受一个可选的上下文参数(改变回调函数里面的this指向)(第2个参数)。

// array.forEach(callback,[thisObject])
//例子更能说明一切:

vardatabase ={
users:["张含韵","戚薇"],
sendEmail:function(user) {
// console.log(this)
if(this.isValidUser(user)) {
console.log("你好,"+user);
}else{
console.log("抱歉,"+user+",你不是本家人");
}
},
isValidUser:function(user) {
return/^张/.test(user);
}
};

//给每个人发邮件
database.users.forEach(// database.users中人遍历
database.sendEmail,//发送邮件
database//使用database代替上面if里面的this
);

//结果:
//你好,张含韵
//抱歉,戚薇,你不是本家人
</script>

3.map:
<script>
// [].map();基本用法跟forEach方法类似:
// array.map(callback, [thisObject]);
// callback的参数也类似:
// [].map(function(value, index, array) {
// ...
// });
//举个例子:求数值项求平方
/*var data = [1, 2, 3, 4];
var arrayOfSquares = data.map(function (item) {
return item * item;
});
alert(arrayOfSquares); // 1, 4, 9, 16
// callback需要有return值,如果没有,就像下面这样:

var data = [1, 2, 3, 4];
var arrayOfSquares = data.map(function() {});
arrayOfSquares.forEach(console.log);*/
//在实际使用的时候,我们可以利用map方法方便获得对象数组中的特定属性值们。

varusers =[
{name:"刘亦菲","email":"[email protected]"},
{name:"戚薇","email":"[email protected]"},
];

varemails = users.map(function(user) {
returnuser.email;
});

console.log(emails.join(", "));

// Array.prototype扩展可以让IE6-IE8浏览器也支持map方法:
/* if (typeof Array.prototype.map != "function") {
Array.prototype.map = function (fn, context) {
var arr = [];
if (typeof fn === "function") {
for (var k = 0; k < this.length; k++) {
arr.push(fn.call(context, this[k], k, this));
}
}
return arr;
};
}*/
</script>

4.reduce:
<script>
//此方法相比上面的方法都复杂,用法如下:
// array.reduce(callback[, initialValue])
// callback函数接受4个参数:之前值、当前值、索引值以及数组本身。initialValue参数可选,表示初始值。
//若指定,则当作最初使用的previous值;
//如果缺少,则使用数组的第一个元素作为previous初始值,同时current往后排一位,相比有initialValue值少一次迭代。

varsum =[1,2,3,4].reduce(function(previous,current,index,array) {
returnprevious+current;
});

console.log(sum);// 10
//说明:

//因为initialValue不存在,因此一开始的previous值等于数组的第一个元素。
//从而current值在第一次调用的时候就是2.
//最后两个参数为索引值index以及数组本身array.
//以下为循环执行过程:

// // 初始设置
// previous = initialValue = 1, current = 2

// //第一次迭代
// previous = (1 + 2) = 3, current = 3

// //第二次迭代
// previous = (3 + 3) = 6, current = 4

// //第三次迭代
// previous = (6 + 4) = 10, current = undefined (退出)





//有了reduce,我们可以轻松实现二维数组的扁平化:

varmatrix =[
[1,2],
[3,4],
[5,6]
];

//二维数组扁平化
varflatten = matrix.reduce(function(previous,current) {
returnprevious.concat(current);
});

console.log(flatten);// [1, 2, 3, 4, 5, 6]



//兼容处理IE6-IE8:
// if (typeof Array.prototype.reduce != "function") {
// Array.prototype.reduce = function (callback, initialValue ) {
// var previous = initialValue, k = 0, length = this.length;
// if (typeof initialValue === "undefined") {
// previous = this[0];
// k = 1;
// }
// if (typeof callback === "function") {
// for (k; k < length; k++) {
// this.hasOwnProperty(k) && (previous = callback(previous, this[k], k, this));
// }
// }
// return previous;
// };
// }

</script>

5.some和every
<script>
// 1.some
// some意指“某些”,指是否“某些项”合乎条件。与下面的every算是好基友,every表示是否“每一项”都要靠谱。用法如下:
// array.some(callback,[ thisObject]);
//例如下面的简单使用:

/* var scores = [5, 8, 3, 10];
// var arr = [2,4,5,2];
var current = 7;

function fn(score) {
return score > current;
}

if (scores.some(fn)) {
alert("ok");
}*/
// if (!arr.some(fn)) {
// alert("ok");
// }
//结果弹出了“ok”文字。 some要求至少有1个值让callback返回true就可以了。显然,8 > 7,因此scores.some(fn)值为true.

//我们自然可以使用forEach进行判断,不过,相比some,不足在于,some只有有true即返回不再执行了。



// 2.every
//跟some类似,不过every表示是否“每一项”都要靠谱。

varscores =[5,8,3,10];
varcurrent =7;

functionhigherThanCurrent(score) {
returnscore> current;
}

if(scores.every(higherThanCurrent)) {
console.log("朕准了!");
}else{
console.log("来人,拖出去斩了!");
}

</script>

猜你喜欢

转载自blog.csdn.net/weixin_39921345/article/details/78786112
今日推荐