Home > Article > Web Front-end > How to use for in loop in JavaScript? What needs attention?
Everyone knows that JavaScript provides two ways to iterate objects:
(1)for loop;
(2)for..in loop;
It must be commonplace for everyone to use a for loop to iterate array objects. However, when using for..in loops, everyone should pay attention. Why do you say this? Everyone, listen to me...
Javascript provides a special loop (that is, the for..in loop), which is used to iterate the properties of an object or each element of an array, for...in The loop counter in the loop is a string, not a number. It contains the name of the current property or the index of the current array element.
Case 1:
//使用for..in循环遍历对象属性 varperson={ name: "Admin", age: 21, address:"shandong" }; for(vari in person){ console.log(i); }
The execution result is:
name
age
address
When traversing an object, the variable i, which is the loop counter, is the attribute name of the object
//使用for..in循环遍历数组 vararray = ["admin","manager","db"] for(vari in array){ console.log(i); }
Execution results:
0
1
2
When traversing an array, the variable i, which is the loop counter, is the index of the current array element
Case 2:
However, it seems that the for..in loop is quite easy to use. However, don’t be too happy too early. Take a look at the following example:
var array =["admin","manager","db"]; //给Array的原型添加一个name属性 Array.prototype.name= "zhangsan"; for(var i in array){ alert(array[i]); }
Run results:
admin
manager
db
zhangsan
Hey, what a wonder, why did a zhangsan appear out of nowhere
Now, let’s see what happens if we use a for loop?
vararray = ["admin","manager","db"]; //给Array的原型添加一个name属性 Array.prototype.name = "zhangsan"; for(var i =0 ; i<array.length; i++){ alert(array[i]); };
Run results:
admin
manager
db
Oh, now I understand, the for..in loop will store the methods and attributes in the prototype of a certain type to be traversed out, so this may cause unexpected errors in the code. In order to avoid this problem, we can use the object's hasOwnProperty() method to avoid this problem. If the object's properties or methods are non-inherited, then the hasOwnProperty() method returns true. That is, the check here does not involve properties and methods inherited from other objects, but only properties created directly in the specific object itself.
Case 3:
vararray = ["admin","manager","db"]; Array.prototype.name= "zhangshan"; for(vari in array){ //如果不是该对象自身直接创建的属性(也就是该属//性是原型中的属性),则跳过显示 if(!array.hasOwnProperty(i)){ continue; } alert(array[i]); }
Run result:
admin
manager
db
Everything is intact again.
The above is the detailed content of How to use for in loop in JavaScript? What needs attention?. For more information, please follow other related articles on the PHP Chinese website!