the question of the subject can be abstracted as:
Will it fall into a dead loop if a new value is inserted into the array in the
for in loop?
like the following code:
var arr = [0, 1, 2]
var i
for (i in arr) {
arr.push(4)
console.log(arr[i])
}
it turns out that it won't. Can you infer that the arr
here only takes a snapshot of all the attributes when for (i in arr)
, so the above code may be equivalent to:
var arr = [0, 1, 2]
var i
var keys=Object.keys(arr)
for (i in keys) {
arr.push(4)
console.log(arr[i])
}
did not check what the specification says, but it should be similar. You will know this kind of problem by testing, and there is no need to check the specification. If you want to find out, check it yourself.
in addition, for (brry [I] in arry) {
this is the second time I have seen this usage,
although I know it is to get index
, key
, value
at the same time.
but I don't think this code is readable.
- has an extra global variable
brry
,
- has an extra line
iPP
traverse the properties of the array
for (i in arr) {
is fine, even if it is used to traverse objects.
var obj={x:1,y:2}
var i,keys=Object.keys(obj)
for (i in keys) {
console.log(i,keys[i],obj[keys[i]])
}
this is also possible, or it is possible to directly use the array manipulation method of ES5
.
var obj={x:1,y:2}
Object.keys(obj).forEach(function(key,index){
console.log(key,index,obj[key])
})
doesn't understand what you're saying has anything to do with your code?
this is sure to happen. The javascript array type is essentially an Object, that changes its value itself wherever it changes. If you are not sure, you can try to write a code to verify it:
for(i in arry) {
array[i] = 'test'
console.log(arry)
}