简体   繁体   English

在for循环迭代中删除数组时会发生什么?

[英]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? 如果CowCow.array被删除,将会发生什么?

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: 即使是这样,大多数情况下也不会返回错误(到目前为止,您正在使用JavaScript请注意,上一次测试会导致错误),这几乎总是会导致奇怪的行为:

 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);
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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