面试题之js数组遍历

版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 https://blog.csdn.net/qq_43168841/article/details/83095607

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) // 
 }
})

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

let obj = {
 name: '前端攻城小牛',
 age: '864305860', //QQ群:864305860
 weight: 'max'
}
for(var key in obj) {
 console.log(key); // name age weight
 console.log(obj[key]); // 全栈开发交流群
 QQ群:864305860 max
}
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 = ['前端攻城狮', '全栈开发交流群', 'QQ群:864305860'];
for (let item of arr) { 
 console.log(item); // 前端攻城狮 全栈开发交流群 QQ群:864305860
}
// 输出数组索引
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:全栈开发交流群 2:Q群:864305860
}

猜你喜欢

转载自blog.csdn.net/qq_43168841/article/details/83095607