在谈for...of前;我们来比较for和for...in的弊端;
1:其中for 循环的最大缺点是需要跟踪计数器和退出条件。老生常谈就不多说了。
2:for...in 它消除了跟踪技术器和退出条件,但是依然需要使用 index 来访问数组的值,让人感觉有点不人性化,此外,当你需要向数组中添加额外的方法(或另一个对象)时,for...in 循环会带来很大的麻烦。因为 for...in 循环循环访问所有可枚举的属性,意味着如果向数组的原型中添加任何其他属性,这些属性也会出现在循环中。
Array.prototype.decimalfy = function() {
for (let i = 0; i < this.length; i++) {
this[i] = this[i].toFixed(2);
}
};
const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const index in digits) {
console.log(digits[index]);
}
Prints:
0
1
2
3
4
5
6
7
8
9
function() {
for (let i = 0; i < this.length; i++) {
this[i] = this[i].toFixed(2);
}
}
For...of 循环
for...of 循环用于循环访问任何可迭代的数据类型。
for...of 循环的编写方式和 for...in 循环的基本一样,只是将 in
替换为 of
,可以忽略索引。简洁方便;
const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const digit of digits) {
console.log(digit);
}