R The for..in cycle trap in JavaScript
Everyone knows that there are two ways toe objects in JavaScript: (1) for loop; (2) for..in cycle; Using a for loop to iterate array objects must be commonplace for everyone. However, when using for..in loops, everyone should pay attention. Why do you say this? Everyone, listen to my story... 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... The loop counter in the in 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); }
//使用for..in循环遍历数组 vararray = ["admin","manager","db"] for(vari in array){ console.log(i); }
var array =["admin","manager","db"]; //给Array的原型添加一个name属性 Array.prototype.name= "zhangsan"; for(var i in array){ alert(array[i]); }
Now, look again What happens when using a for loop?
vararray = ["admin","manager","db"]; //给Array的原型添加一个name属性 Array.prototype.name = "zhangsan"; for(var i =0 ; i<array.length; i++){ alert(array[i]); };
vararray = ["admin","manager","db"]; Array.prototype.name= "zhangshan"; for(vari in array){ //如果不是该对象自身直接创建的属性(也就是该属//性是原型中的属性),则跳过显示 if(!array.hasOwnProperty(i)){ continue; } alert(array[i]); }
Everything again It's as good as ever, hey, I don't know, comrades, after reading this, what do you think? How do you feel? Do you have the feeling of "pushing away the clouds and seeing the sunny sky", haha