for...in 遞歸的對象是object的屬性
for...of 遞歸的對象是一系列可遞歸的可迭代對象,例如Array主到,String, Map, Set等
搬官方例子過來以便參考理解:
for...in 遞歸object的屬性:
var obj = {a: 1, b: 2, c: 3};
for (const prop in obj) {
console.log(`obj.${prop} = ${obj[prop]}`);
}
// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"
for...of 遞歸Array:
let iterable = [10, 20, 30];
for (let value of iterable) {
value += 1;
console.log(value);
}
// 11
// 21
// 31
for...of遞歸String:
let iterable = 'boo';
for (let value of iterable) {
console.log(value);
}
// "b"
// "o"
// "o"
for...of遞歸Map:
let iterable = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (let entry of iterable) {
console.log(entry);
}
// ['a', 1]
// ['b', 2]
// ['c', 3]
for (let [key, value] of iterable) {
console.log(value);
}
// 1
// 2
// 3
for...of還可以遞歸其他的類型意蛀,請看下面的第二個鏈接傍妒,獲取官網更多例子
參考:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of