您的位置:首页 > Web前端 > JavaScript

js迭代循环

2022-04-09 17:51 2591 查看

一、for loop

for (let i = 0; i < products.length; i++) {
console.log(products[i]);
}

支持循环中断,可以用

break
中断

二、forEach()循环

forEach()
Array.prototype
上的方法,可以使用它对数组进行循环遍历,forEach中传入要执行的回调函数,函数有三个参数。第一个参数为数组元素(必选),第二个参数为数组元素索引值(可选),第三个参数为数组本身(可选)。没有返回值,只是针对每个元素调用回调函数

let arr = ['a','b','c','d','e'];
arr.forEach((item,index,arr)=> {
console.log(item);   // a b c d e
console.log(index);  // 0 1 2 3 4
console.log(arr);    // ['a','b','c','d','e']
})

不需要先去计算数组的总数才能循环,直接用就可以了

forEach
不支持中断循环,如果不需要条件中断循环数组的话,采用forEach是最好的选择.

三、map()循环

map()
中传入要执行的回调函数,函数有三个参数。第一个参数为数组元素(必选),第二个参数为数组元素索引值(可选),第三个参数为数组本身(可选)。map() 按照原始数组元素顺序依次处理元素,返回值是一个新的数组,每个元素为调用回调函数的结果

//栗子一:
let arr = [
{name: 'a', age:'18'},
{name: 'b', age:'20'},
{name: 'c', age:'19'},
];
arr.map(function(item, index){
if(item.name === 'b'){
console.log(index) // 1
}
})

//栗子二:
let list = [1, 2, 3, 4, 5];
let other = list.map((item, index) => {
return item* 2;
});
console.log(other); // [2, 4, 6, 8, 10]

四、filter()循环

filter()
中传入要执行的回调函数,函数有三个参数。第一个参数为数组元素(必选),第二个参数为数组元素索引值(可选),第三个参数为数组本身(可选)。filter() 方法会依次执行数组的每个元素,返回一个符合回调函数条件的元素组成的数组

let list = [1, 2, 3, 4, 5];
let other = list.filter((d, i) => {
return d % 2;
});
console.log(other); // [1, 3, 5]

五、some()循环

some()
中传入要执行的回调函数,函数有三个参数。第一个参数为数组元素(必选),第二个参数为数组元素索引值(可选),第三个参数为数组本身(可选)。some() 方法会依次执行数组的每个元素,如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测;如果没有满足条件的元素,则返回false。

let list = [1, 2, 3, 4, 5];
list.some((d, i) => {
console.log(d, i); // 1,0   2,1   3,2   4,3
return d > 3; // return true
});

六、every()循环

every()
中传入要执行的回调函数,函数有三个参数。第一个参数为数组元素(必选),第二个参数为数组元素索引值(可选),第三个参数为数组本身(可选)。every() 方法会依次执行数组的每个元素,如果有一个元素不满足条件,则表达式返回false , 剩余的元素不会再执行检测;如果所有元素都满足条件,则返回true。

七、for...in...

for...in
循环可用于循环对象和数组,推荐用于循环对象,可以用来遍历json

let obj = {
name: '王大锤',
age: '18',
weight: '70kg'
}
for(var key in obj) {
console.log(key);       //  name age weight
console.log(obj[key]);  //  王大锤 18 70kg
}
let arr = ['a','b','c','d','e'];
for(var key in arr) {
console.log(key);  //  0 1 2 3 4 返回数组索引
console.log(arr[key]) //  a b c d e
}

for...in不应该用于迭代一个 Array,其中索引顺序很重要。并且如果为了过滤迭代继承的属性方法,又要用hasOwnProperty这些方法,非常繁琐。总之通常情况下不会去要迭代继承而来的属性,因此不太推荐使用for...in...。

八、for...of...

在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句。

for...of提供了三个新方法:

  • key()是对键名的遍历;
  • value()是对键值的遍历;(默认)
  • entries()是对键值对的遍历;
let arr = ['科大讯飞', '政法BG', '前端开发'];
for (let item of arr) {
console.log(item); //  科大讯飞  政法BG  前端开发
}
// 输出数组索引
for (let item of arr.keys()) {
console.log(item);  // 0 1 2
}
// 输出内容和索引
for (let [item, val] of arr.entries()) {
console.log(item + ':' + val); //  0:科大讯飞  1:政法BG  2:前端开发
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: