js 列表几种循环的比较

数组

遍历

普通遍历

最简单的一种,也是使用频率最高的一种。

let arr = ['a', 'b', 'c', 'd', 'e']
for (let i = 0; i < arr.length; i++) {
  console.log(i, ' => ', arr[i])
}

 

优化: 缓存数组长度:

let arr = ['a', 'b', 'c', 'd', 'e']
for (let i = 0, len = arr.length; i < len; i++) {
  console.log(i, ' => ', arr[i])
}

 

使用临时变量,将长度缓存起来,避免重复获取数组长度,当数组较大时优化效果才会比较明显。

for-in

这个循环很多人爱用,但实际上,经分析测试,在众多的循环遍历方式中它的效率是最低的。

let arr = ['a', 'b', 'c', 'd', 'e']
for (let i in arr) {
  console.log(i, ' => ', arr[i])
}

 

for-of

这种方式是es6里面用到的,性能要好于forin,但仍然比不上普通for循环。

let arr = ['a', 'b', 'c', 'd', 'e']
let index = 0
for (let item of arr) {
  console.log(index++, ' => ', item)
}

 

forEach

数组自带的foreach循环,使用频率较高,实际上性能比普通for循环弱。

let arr = ['a', 'b', 'c', 'd', 'e']
arr.forEach((v, k) => {
  console.log(k, ' => ', v)
})

 

forEach接受第三个参数,指向原数组,没有返回值,对其进行操作会改变原数组对象

let ary = [12, 23, 24, 42, 1]
let res = ary.forEach((item, index, input) => {
   input[index] = item * 10
})
console.log(res) //-->undefined
console.log(ary) //-->会对原来的数组产生改变

 

转载于:https://www.cnblogs.com/randomlee/p/10619384.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值