forEach
- 三個參數(shù)颅痊,第一個value, 第二個 index, 第三個數(shù)組體。
- 適用于 數(shù)組局待,set斑响,map菱属,不適應于 字符串,Object舰罚。
- 無法修改和刪除集合數(shù)據(jù)纽门,效率和for循環(huán)相同,不用關心集合下標的返回营罢。
-
不能終止循環(huán)赏陵,break,continue不能使用饲漾。
栗子(Array 循環(huán)):
let arr = [1, "ding", null, 5, true, undefined];
arr.forEach(function(value, index, a) {
console.log("value:", value, "index:", index, "a:", a);
})
image.png
栗子(Set, Map 循環(huán)):
let obj = {
name: "dingding",
age: 20,
male: false,
city: "北京"
};
let set = new Set(arr);
let map = new Map();
map.set('obj', obj);
map.set("color", "pink");
set.forEach((item, index, a) => {
console.log(item, "------", index, "------:", a);
})
console.log('\n');
map.forEach(function(item, index, a){
console.log(item, "++++++", index, "+++++++", a);
})
image.png
map
forEach()返回值是undefined蝙搔,不可以鏈式調用。
map()返回一個新數(shù)組考传,原數(shù)組不會改變吃型。
for in
- 索引為字符串
- 多用于遍歷對象,json僚楞,數(shù)組勤晚,無順序,增加了轉換過程所以開銷比較大
- 可擴展屬性(自定義屬性)也會遍歷
- 支持break, continue
- 某些情況下泉褐,for in 循環(huán)會以任意順序遍歷鍵名
- 循環(huán)讀取鍵名
栗子:
for(let item in obj) {
console.log(item, ":", obj[item]);
if(item == "age") delete obj[item]; //刪除屬性成功
}
console.log("obj:", obj);
image.png
栗子:(可擴展屬性也會遍歷)
arr.name = "red";
for(let i in arr) {
console.log(i, ":", arr[i]);
}
console.log("arr", arr)
image.png
for of
- ES6新引入的特性赐写,是目前遍歷數(shù)組最好的方法,可以用在set兴枯,map血淌,類數(shù)組矩欠,字符串上财剖,但是不支持原生的Object遍歷。
- 不會遍歷可擴展屬性(自定義屬性)
- 支持break, continue
- 循環(huán)讀取鍵值