JS 几种常见的遍历方式
for循环
- 普通的写法
let arr = [1,2,3]; for(let i =0;i<arr.length;i++){ console.log(arr[i]) // 1 2 3 }
- 改进的写法
因为每次arr.length都会重复获取数组的长度,因此会导致性能的损失
所以我们可以先使用一个变量
将其缓存
起来,从而达到性能的优化let arr = [1,2,3]; let len = arr.length for(let i =0;i<len;i++){ console.log(arr[i]) // 1 2 3 }
for in 循环
- 用于遍历
数组
或者对象
的属性const obj = { a: 1, b: 2, c: 3 } for(let i in obj){ console.log(i,obj[i]); // a 1 b 2 c 3 }
for of 循环
- 用于遍历
数组
,不能用于遍历对象
,否则会报错
- 遍历对象
const obj = { a: 1, b: 2, c: 3 } for(let i of obj){ console.log(i,obj[i]); // TypeError: obj is not iterable }
- 遍历数组
let arr = [11,22,33]; for(let i of arr){ console.log(i); // 11 22 33 }
forEach循环
- 用于遍历
数组
中的值使用forEach时,要使用一个function回调函数。
let arr = [1,2,3]; arr.forEach(function(i){ console.log(i);// 1 2 3 })
map方法
- 不改变原数组,返回回调函数里的结果
let arr = [1,2,3]; arr.map(function(i){ console.log(i);// 1 2 3 })