Home > Web Front-end > JS Tutorial > body text

js hasownproperty usage example_basic knowledge

WBOY
Release: 2016-05-16 16:57:39
Original
1314 people have browsed it

For example:
There is such a piece of code:

Copy the code The code is as follows:

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

What will be output at this time? Of course it is 0:1 1:2 2:3
But if you add Array.prototype.say = "hello";
before for in, what will be output when you run it again?
Copy code The code is as follows:

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

See, at this time, it will output the properties of the prototype
In many cases, we don’t need to traverse the properties of its prototype. Another reason is that the object we are using now ,We cannot guarantee that other developers have ,added some attributes to its prototype? So, let’s filter the properties of our object. This time we use the hasOwnProperty method, as follows:
Copy code Code As follows:

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

Think about it again, what will be output now? Of course it's 0:1 1:2 2:3.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!