這邊幫大家整理 for in vs for of vs foreach
- for in 取得是 array或object的key
- for of 取得的是值,但沒辦法直接用再 object上
- foreach key、value都可以取得,但不能 break or return
for in of | foreach | |
break | Y | N |
return | Y | N |
for in | for of | foreach | |
迭代指 iterator 的值 | index | value | index / value |
可直接用在 object上 | Y | N | N |
而 for of / foreach 若要巡覽object中的各值,
則要用到Object物件把object轉成array,有以下三種方法
- Object.values()
- Object.keys()
- Object.entries()
範例程式代碼:
let array = [3, 5, 7]; // 回傳「key」 for (let i in array) { console.log(i); // "0", "1", "2" } // 回傳「value」 for (let i of array) { console.log(i); // 3, 5, 7 } array.foo = 'hello'; //新增foo屬性名稱 //會讀取到陣列新增的屬性名稱 for (let i in array) { console.log(i); // "0", "1", "2", "foo" } //不會 for (let i of iterable) { console.log(i); // 3, 5, 7 } const object1 = { a: 'somestring', b: 42 }; //for of 迭代object的方法 for (const [key, value] of Object.entries(object1)) { console.log(`${key}: ${value}`); } // a: somestring // b: 42 //foreach 基本用法 array.forEach((value, index, arrayPointer) => {arrayPointer[index] = value + 1;}); array; // [4,6,8] const obj = { name: 'Jean-Luc Picard', rank: 'Captain' }; //foreach 迭代object的方法 Object.keys(obj).forEach(key => { console.log(key, obj[key]); }); //name, Jean-Luc Picard //rank, Captain Object.values(obj).forEach(val => { console.log(val); }); //Jean-Luc Picard //Captain Object.entries(obj).forEach(entry => { const [key, value] = entry; console.log(key, value); }); //name, Jean-Luc Picard //rank, Captain
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記