10th week task -1

1:
For each ... in
For...in Examples
For...of
对以上的内容进行
Examples和Explanation

(1)For...in      以任意顺序遍历一个对象的可枚举属性。对于每个不同的属性,语句都会被执行

for(variable in object){...}

var obj = {a:1, b:2, c:3};
    
for (var prop in obj) {
  console.log("obj." + prop + " = " + obj[prop]);
}

// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"

 

(2)For each...in 

for each (variable in object) {

statement//语句

}

 

var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8};

for each (var item in obj) {
  sum += item;
}

print(sum); // 输出"26",也就是5+13+8的值

(3)For ...of

S6标准引入了新的iterable类型,Array、Map和Set都属于iterable类型;

                    具有iterable类型的集合可以通过for...of循环来遍历;

                      只循环集合本身的元素。

 

var a = ["A","B","C"];
var s = new Set(["A","B","C"]);
var m = new Map([[1,"x"],[2,"y"],[3,"z"]]);
for (var x of a){
     alert(x);
}
for (var x of s){
     alert(x);
}
for (var x of m){
     alert(x[0]+"="+x[1]);
}

posted @ 2018-11-08 23:19  sasuke。  阅读(91)  评论(0编辑  收藏  举报