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