10th week task -1
阿新 • • 發佈:2018-11-08
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]); }