0

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?

leonylyner
  • 117
  • 2
  • 7
  • Depends on the language. Mostly will throw an Exception, or ended with a fatal Error. Some will "work" cause inside a loop the field are duplicate so you can't modify them, but it will result in strange output. In every case do not do that – vincrichaud Mar 20 '18 at 14:05
  • Thanks, how should I fix it? – leonylyner Mar 20 '18 at 14:07
  • Just do not do that – vincrichaud Mar 20 '18 at 14:12
  • https://stackoverflow.com/questions/9882284/looping-through-array-and-removing-items-without-breaking-for-loop – Sam Mar 20 '18 at 14:12
  • What do you mean by *removed*? Are you only concerned about the behavior of a `for in` loop? If you `delete` a key of the object which keys are being iterated, then the iteration will not go through this key. And If you delete the object from its parent object, then everything will run as usual, since the loop keeps a live access to the object and doesn't go through accessing it from the parent object at every iteration. – Kaiido Mar 20 '18 at 14:25

2 Answers2

0

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

messerbill
  • 5,499
  • 1
  • 27
  • 38
0

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);
    }
 }
vincrichaud
  • 2,218
  • 17
  • 34