对于前端的循环遍历我们知道有
- 针对js数组的forEach()、map()、filter()、reduce()方法
- 针对js对象的for/in语句(for/in也能遍历数组,但不推荐)
- 针对jq数组/对象的$.each()方法
在语法和参数上他们有什么不同呢?
1.forEach: array.forEach(function(currentValue,index,arr), thisValue)
2.map: array.map(function(currentValue,index,arr), thisValue)
3.filter: array.filter(function(currentValue,index,arr), thisValue)
4.reduce: array.reduce(function(total,currentValue,index,arr), thisValue)
5.$.each: $.each( object/array, function(index,elment) );//jQuery的遍历方法,这里先不多说
6.for/in: for (var key in object) { //... }
下面来看看这几个方法不同的地方
定义:
-
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
-
map()方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map()方法按照原始数组元素顺序依次处理元素 -
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。没有到没有符合条件时返回空数组。
-
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值
举几个例子:
1、一般的遍历数组的方法:
var array = [1,2,3,4,5,6,7];
for (var i = 0; i < array.length; i++) {
console.log(i,array[i]); // 输出1 2 3 4 5 6 7
}
2、用for in的方遍历数组
var array = [1,2,3,4,5,6,7];
for(let index in array) {
console.log(index,array[index]);
//输出:
// 0 1
// 1 2
// 2 3
// 3 4
// 4 5
// 5 6
// 6 7
};
3、forEach
array.forEach(v=>{
console.log(v); // 输出1 2 3 4 5 6 7
});
array.forEach(function(v){
console.log(v); // 输出1 2 3 4 5 6 7
});
4、用for in不仅可以对数组,也可以对enumerable对象操作
var A = {a:1,b:2,c:3,d:"hello world"};
for(let k in A) {
console.log(k,A[k]); // 输出: 1 2 3 hello world
}
5、在ES6中,增加了一个for of循环,使用起来很简单
for(let v of array) {
console.log(v); // 输出1 2 3 4 5 6 7
};
let s = "helloabc";
for(let c of s) {
console.log(c); // 输出 h e l l o a b c
}
for…in与for…of的区别
for…in循环会遍历一个object所有的可枚举属性。
for…of会遍历具有iterator接口的数据结构
for…in 遍历(当前对象及其原型上的)每一个属性名称,而 for…of遍历(当前对象上的)每一个属性值
Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};
let iterable = [3, 5, 7];
iterable.foo = "hello";
for (let i in iterable) {
console.log(i); // 输出 0, 1, 2, "foo", "arrCustom", "objCustom"
}
for (let i of iterable) {
console.log(i); // 输出 3, 5, 7
}