Skip to content

Commit 52ba057

Browse files
committed
edit iterator/for...of
1 parent b12393b commit 52ba057

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

docs/iterator.md

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -525,10 +525,10 @@ arr.forEach(function (element, index) {
525525
});
526526
```
527527

528-
JavaScript原有的`for...in`循环,只能获得对象的键名,不能直接获取键值。ES6提供for...of循环,允许遍历获得键值。
528+
JavaScript原有的`for...in`循环,只能获得对象的键名,不能直接获取键值。ES6提供`for...of`循环,允许遍历获得键值。
529529

530530
```javascript
531-
var arr = ["a", "b", "c", "d"];
531+
var arr = ['a', 'b', 'c', 'd'];
532532

533533
for (let a in arr) {
534534
console.log(a); // 0 1 2 3
@@ -541,6 +541,23 @@ for (let a of arr) {
541541

542542
上面代码表明,`for...in`循环读取键名,`for...of`循环读取键值。如果要通过`for...of`循环,获取数组的索引,可以借助数组实例的`entries`方法和`keys`方法,参见《数组的扩展》章节。
543543

544+
`for...of`循环调用遍历器接口,数组的遍历器接口只返回具有数字索引的属性。这一点跟`for...in`循环也不一样。
545+
546+
```javascript
547+
let arr = [3, 5, 7];
548+
arr.foo = 'hello';
549+
550+
for (let i in arr) {
551+
console.log(i); // "0", "1", "2", "foo"
552+
}
553+
554+
for (let i of arr) {
555+
console.log(i); // "3", "5", "7"
556+
}
557+
```
558+
559+
上面代码中,`for...of`循环不会返回数组`arr``foo`属性。
560+
544561
### Set和Map结构
545562

546563
Set和Map结构也原生具有Iterator接口,可以直接使用`for...of`循环。

0 commit comments

Comments
 (0)