File tree Expand file tree Collapse file tree 1 file changed +19
-2
lines changed Expand file tree Collapse file tree 1 file changed +19
-2
lines changed Original file line number Diff line number Diff line change @@ -525,10 +525,10 @@ arr.forEach(function (element, index) {
525
525
});
526
526
```
527
527
528
- JavaScript原有的` for...in ` 循环,只能获得对象的键名,不能直接获取键值。ES6提供for ...of循环 ,允许遍历获得键值。
528
+ JavaScript原有的` for...in ` 循环,只能获得对象的键名,不能直接获取键值。ES6提供 ` for ...of ` 循环 ,允许遍历获得键值。
529
529
530
530
``` javascript
531
- var arr = [" a " , " b " , " c " , " d " ];
531
+ var arr = [' a ' , ' b ' , ' c ' , ' d ' ];
532
532
533
533
for (let a in arr) {
534
534
console .log (a); // 0 1 2 3
@@ -541,6 +541,23 @@ for (let a of arr) {
541
541
542
542
上面代码表明,` for...in ` 循环读取键名,` for...of ` 循环读取键值。如果要通过` for...of ` 循环,获取数组的索引,可以借助数组实例的` entries ` 方法和` keys ` 方法,参见《数组的扩展》章节。
543
543
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
+
544
561
### Set和Map结构
545
562
546
563
Set和Map结构也原生具有Iterator接口,可以直接使用` for...of ` 循环。
You can’t perform that action at this time.
0 commit comments