Js hasownproperty USES examples

  • 2020-03-30 02:11:19
  • OfStack

Such as:
Here's a piece of code:


var array = [];
array.push(1);
array.push(2);
array.push(3);
for(var i in array) {
console.log(i+":"+array[i]);
}

So what's going to be output? Of course it's 0:1, 1:2, 2:3
But if I put Array. Prototype. Say = "hello" before "for in ";
What will be output if I run it again?

0:1 1:2 2:3 say:hello

See, at this point, it outputs the properties of the stereotype
A lot of times, we don't have to go through the properties of its prototype, and the other reason is that the object that we're using right now, we can't guarantee that other developers are going to put some properties on its prototype. So let's filter the properties of our object, and we'll use the hasOwnProperty method as follows:

for(var i in array){
if(array.hasOwnProperty(i)) {
console.log(i+":"+array[i]);
}
}

Now, what is the output going to be? Of course it's 0:1, 1:2, 2:3.


Related articles: