JavaScript中有多种循环Array的方式,你是否常常分不清他们的细微差别,和适用场景。本文将详细梳理各间的优缺点,整理成表以便对比。
循环 | 可访问element | 可访问index | 可迭代property | 支持中断 | 支持await | 支持任意位置开始 |
---|---|---|---|---|---|---|
for | √ | √ | × | √ | √ | √ |
for in | √ | × | √ | √ | √ | × |
forEach | √ | √ | × | × | × | × |
for of | √ | √ | × | √ | √ | × |
for (ES1)
这个循环方式历史悠久,从ECMAScript 1就被支持。
const arr = ['a', 'b', 'c'];
arr.prop = 'property value';
for (let index=0; index < arr.length; index++) {
const elem = arr[index];
console.log(index, elem);
}
// Output:
// 0, 'a'
// 1, 'b'
// 2, 'c'
for
循环方式通用,迭代过程可以访问元素和当前元素下标索引,但是语法上略显冗长。
for in (ES1)
for in
的历史同for
一样悠久。
const arr = ['a', 'b', 'c'];
arr.prop = 'property value';
for (const key in arr) {
console.log(key);
}
// Output:
// '0'
// '1'
// '2'