JS陣列中(for...in)和(for...of)的區別

katesharing發表於2024-08-15

stackoverflow上有一個類似的問題

https://stackoverflow.com/questions/29285897/difference-between-for-in-and-for-of-statements

 //for..of與for..in的區別
    var arr = [3, 5, 7];
    arr.foo = "hello";

    for (var i in arr) {
        console.log("for in:", i); // logs "0", "1", "2", "foo"
    }

    for (var i of arr) {
        console.log("for of:", i); // logs "3", "5", "7"
        // it doesn't log "3", "5", "7", "hello"
    }

有人回覆的答案如下:大概意思應該就是for in輸出的是物件的屬性;而for of 輸出的是陣列的每一個值

相關文章