forEach、for...in和for..of比較
阿新 • • 發佈:2018-12-06
forEach是遍歷陣列中的值:
var arr=['one','two','three'];
arr.forEach(function(value){
console.log(value);
})
//one
//two
//three
這種寫法的問題在於,無法中途跳出forEach迴圈,break命令或return命令都不管用。
for…in是遍歷陣列的鍵名
var arr=['one','two','three'];
for(var i in arr){
console.log(i);
}
//0
//1
//2
缺點是:
陣列的鍵名是數字,但是for…in迴圈是以字串作為鍵名,“0”、“1”、"2"等
for…in不僅可以遍歷數字鍵名,還可以遍歷手動新增的其他的鍵,甚至包括原型鏈上的鍵
var arr=['one','two','three'];
arr.foo='four';
for(var i in arr){
console.log(i);
}
//0
//1
//2
//foo
某些情況下,for…in會以任意順序遍歷鍵名
for…in主要是為遍歷物件而設計,不適合遍歷陣列。
for…of可以遍歷資料結構中部署了Symbol.iterator屬性的成員
for…of可以使用的範圍包括陣列、Set和Map結構,某些類似陣列的物件(比如arguments物件、DOM NodeList物件)、Generator物件,以及字串。
//陣列中的遍歷器只返回具有數字索引的屬性
var arr= ['one','two','three'];
arr.foo='four';
for(var i of arr){
console.log(i);
}
//one
//two
//three
//Set和Map
var set=new Set(["a","b","a","c"]);
for(var i of set){
console.log(i);
}
//a
//b
//c
var map=new Map();
map.set("age","18");
map.set("name","yf")
for(var [key,value] of map){
console.log(key+":"+value);
}
//age:18
//name:yf
//字串
let str="hello";
for(let val of str){
console.log(val);
}
//h e l l o
for…of可以通過break、continue和return實現跳出迴圈