1. 程式人生 > >for...of...迴圈和Map物件

for...of...迴圈和Map物件

for相關迴圈也衍生了多種,有普通for迴圈、for...in...迴圈、for...of...迴圈。

普通for迴圈

var arr=[1,2,3,4];
for(var i=0; i<arr.length; i++){...}

for...in...迴圈

var arr=["Tony","Tom","Jack","Mali"];
for(var i in arr){
    console.log(i);    //返回結果0,1,2,3
}

for...in...迴圈不僅僅用於陣列遍歷,還適用於json。

var json={
    "student":"Tony",
    "teacher":"Tom",
    "class":"終極一班",
    "school":"紅花小學"
};
for(var i in json){...}

for...of...迴圈

var arr=["Tony","Tom","Jack","Mali"];
for(var i of arr){
    console.log(i);    //返回結果Tony,Tom,Jack,Mali
}

for...of...迴圈所得結果是陣列的value值,而for...in...迴圈所得是索引值。那麼for...of...迴圈又如何得到index索引值呢?

var arr=["Tony","Tom","Jack","Mali"];
for(var i of arr.keys()){
    console.log(i);    //0,1,2,3
}

那得到key-value形式的結果

var arr=["Tony","Tom","Jack","Mali"];
for(var i of arr.entries()){
    console.log(i); 
}

所得結果: 

陣列的遍歷都可以實現,那for...of...迴圈json會怎麼樣呢?

var json={
    "student":"Tony",
    "teacher":"Tom",
    "class":"終極一班",
    "school":"紅花小學"
};
for(var i of json){
    console.log(json[i]);    //報錯json is not iterable
}

事實證明,for...of...迴圈不能遍歷json。其實,for...of...迴圈最大的用途是為了迴圈Map物件。

那Map物件又為何物呢?

Map物件,和json相似,定義的格式上也是一種key-value形式。Map物件為了和for...of...迴圈配合而生的。

定義Map物件

var map=new Map();

set方法設定Map物件內容

map.set("student","Tony");
map.set("teacher","Tom");

get方法設定Map物件內容

var map = new Map();
map.set("student","Tony");
map.set("teacher","Tom");
map.set("class","初三五班");

console.log(map.get("class"));    //返回 初三五班

delete方法刪除Map物件內容

map.delete("teacher");

遍歷Map物件

在寫for...of...迴圈之前,我們來測驗一下for..in..迴圈是否可以適用Map物件。

var map = new Map();
map.set("student","Tony");
map.set("teacher","Tom");
map.set("class","初三五班");
for(var name in map){
    console.log(name);    //無效果
}

試驗可知,for...in..迴圈Map物件。之前也說了Map物件的產生就是為了更好的發揮for...of...迴圈的作用。

var map = new Map();
map.set("student","Tony");
map.set("teacher","Tom");
map.set("class","初三五班");
for(var name of map){
    console.log(name);
}

所得結果:

for...of...迴圈遍歷Map物件的其他用法

返回key-value形式結果

var map = new Map();
map.set("student","Tony");
map.set("teacher","Tom");
map.set("class","初三五班");
for(var [name,value] of map){
    console.log(name,value);
}

for...of...迴圈的完整寫法

var map = new Map();
map.set("student","Tony");
map.set("teacher","Tom");
map.set("class","初三五班");
for(var name of map.entries()){
    console.log(name);
}

只返回key結果

var map = new Map();
map.set("student","Tony");
map.set("teacher","Tom");
map.set("class","初三五班");
for(var name of map.keys()){
    console.log(name);
}

只返回value結果

var map = new Map();
map.set("student","Tony");
map.set("teacher","Tom");
map.set("class","初三五班");
for(var val of map.values()){
    console.log(val);
}