面试题之js数组遍历

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提供了三个新方法:

  1. key()是对键名的遍历;
  2. value()是对键值的遍历;
  3. 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
}
复制代码

总结: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


转载于:https://juejin.im/post/5bc5b379e51d450e99437d53

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值