简体   繁体   中英

What happens when array is deleted during a for-loop iteration?

For example,

for (i in Cow.array){...}

If either Cow or Cow.array is removed, what will happen?

Also, if error occurs, how can I fix it?

Even this is will mostly not return in an error (so far you are using JavaScript - note that the last test results in an error) this will nearly always end up in strange behaviour:

 let myArr = [1,2,3,4] let myArr2 = [1,2,3,4] let myArr3 = [1,2,3,4] for (let i = 0; i < myArr.length; i++) { console.log("test without reomving: " + myArr[i]) } for (let i = 0; i < myArr.length; i++) { console.log("test with removing: " + myArr[i]) myArr.splice(i, 1); } for (let i = 0; i < myArr2.length; i++) { console.log("last test: " + myArr[i]) myArr2 = myArr2.splice(i, 1); } for (let i = 0; i < myArr3.length; i++) { console.log("very last test: " + myArr[i]) myArr3 = null } 

i strongly recommend NOT to do this

If your goal is to modify an array while looping on it. Try to avoid it as much as possible.

If you have to, use a copy of your array to iterate and modify your original array.

let myArray = [1, 2, 3, 4, 5]
let copy = myArray
for(let i=0; i<copy.length; i++) {
    //do stuff
    // for example remove number 3
    if(i == 3) {
        myArray.splice(i, 1);
    }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM