js数组遍历总结

2019-08-22  本文已影响0人  紫痕蓝羽

js中的数组遍历是项目中经常用到的,在这里将几种方法做个对比。
for循环:使用评率最高,也是最基本的一种遍历方式。
let arr = ['a','b','c','d','e'];
for (let i = 0, len = arr.length; i < len; i++) {
console.log(i); // 0 1 2 3 4
console.log(arr[i]); //a b c d e
}
forEach()循环: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']
})
map循环:map()中传入要执行的回调函数,函数有三个参数。第一个参数为数组元素(必选),第二个参数为数组元素索引值(可选),第三个参数为数组本身(可选)
var arr = [
{name:'a',age:'18'},
{name:'b',age:'19'},
{name:'c',age:'20'}
];
arr.map(function(item,index) {
if(item.name == 'b') {
console.log(index) // 1
}
})
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...of循环:可循环数组和对象,推荐用于遍历数组。
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:前端开发
}
总结:forEach、map、filter、reduce、every、some 都会有 break 和 continue 不生效的问题,因为是在function中,但function解决了闭包陷阱的问题;要使用 break、continue 可以使用 for、for...in、for...of、while。用于遍历数组元素使用:for(),forEach(),map(),for...of 用于循环对象属性使用:for...in

上一篇下一篇

猜你喜欢

热点阅读