for...in引發的思考

kirian發表於2019-05-03

for...in in python

lists = [1,2,3,4,5,6,7,8,9]
lists1 = [2,3,4,5,6,7,8,9]
list2 = [2,4,5,6,7,8,9]

for i in lists:
    print(i)
    if i < 5:
        lists.remove(i)
print(lists)  // [2,4,5,6,7,8,9]
複製程式碼

for...in in javascript

此處MDN不建議對Array使用for...in,因為for...in遍歷的是物件的所有可列舉屬性(自有的、繼承的、可列舉的、非Symbol的)並不保證順序(迭代順序依賴環境)

let lists=[1,2,3,4,5,6,7,8,9]

for(let i in lists){
    console.log(i,typeof i) // string
}

for(let i in lists) {             
  if(i<5){
    lists.splice(lists.indexOf(i),1)
  }
}
console.log(lists) // [1, 2, 3, 4]
複製程式碼

物件的所有可列舉屬性內容不等於Object.keys()的內容

Array.prototype.b=()=>{}
let lists=[1,2,3,4,5,6,7,8,9]
lists.a='a'

console.log(Object.keys(lists))

let inKeys=[]
for(let i in lists){
    inKeys.push(i)
}

console.log(inKeys)

// (10) ["0", "1", "2", "3", "4", "5", "6", "7", "8", "a"]
// (11) ["0", "1", "2", "3", "4", "5", "6", "7", "8", "a", "b"]
複製程式碼

Object.keys() 方法會返回一個由一個給定物件的自身可列舉屬性組成的陣列,陣列中屬性名的排列順序和使用 for...in 迴圈遍歷該物件時返回的順序一致。

注意上述文字自身可列舉屬性,順序一致但是內容不一致哦~,再次強調for...in遍歷的是一個物件自有的、繼承的、可列舉的、非Symbol的屬性

for...of in javascript

for...of 語句遍歷可迭代物件定義要迭代的資料

let lists=[1,2,3,4,5,6,7,8,9]

for(let i of lists){
    console.log(i,typeof i) // number
}

for(let i of lists) {             
  if(i<5){
    console.log(i,' in ',lists,' = ',lists.indexOf(i));
    lists.splice(lists.indexOf(i),1)
  }
}
console.log(lists) // [2, 4, 5, 6, 7, 8, 9]

// 1 " in " (9) [1, 2, 3, 4, 5, 6, 7, 8, 9] " = " 0
// 3 " in " (8) [2, 3, 4, 5, 6, 7, 8, 9] " = " 1
// (7) [2, 4, 5, 6, 7, 8, 9]
複製程式碼
for(let i of lists) {             
  console.log(i,' in ',lists,' = ',lists.indexOf(i));
  lists.splice(lists.indexOf(i),1)
}
console.log(lists) // [2, 4, 6, 8]
// 1 " in " (9) [1, 2, 3, 4, 5, 6, 7, 8, 9] " = " 0
// 3 " in " (8) [2, 3, 4, 5, 6, 7, 8, 9] " = " 1
// 5 " in " (7) [2, 4, 5, 6, 7, 8, 9] " = " 2
// 7 " in " (6) [2, 4, 6, 7, 8, 9] " = " 3
// 9 " in " (5) [2, 4, 6, 8, 9] " = " 4
// (4) [2, 4, 6, 8]
複製程式碼

等同於

for(let index = 0;index<lists.length;index++){
    let i=lists[index]
    console.log(i,' in ',lists,' = ',index);
    lists.splice(lists.indexOf(i),1)
}
console.log(lists) // [2, 4, 6, 8]
// 1 " in " (9) [1, 2, 3, 4, 5, 6, 7, 8, 9] " = " 0
// 3 " in " (8) [2, 3, 4, 5, 6, 7, 8, 9] " = " 1
// 5 " in " (7) [2, 4, 5, 6, 7, 8, 9] " = " 2
// 7 " in " (6) [2, 4, 6, 7, 8, 9] " = " 3
// 9 " in " (5) [2, 4, 6, 8, 9] " = " 4
// (4) [2, 4, 6, 8]
複製程式碼

for...in生成fibonacci數列

function* fibonacci() { // 一個生成器函式
    let [prev, curr] = [0, 1];
    for (;;) { // while (true) {
        [prev, curr] = [curr, prev + curr];
        yield curr;
    }
}
 
for (let n of fibonacci()) {
     console.log(n); 
    // 當n大於1000時跳出迴圈
    if (n >= 1000)
        break;
}
複製程式碼

相關文章