Home  >  Article  >  Web Front-end  >  Example introduction to for-in traversal method in JavaScript_javascript skills

Example introduction to for-in traversal method in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:00:351112browse

Summary: The loop counter of the for-in traversal method is of string type. When traversing the object, it is the object attribute/method name. When traversing the array, it is the array element subscript index. Unlike the ordinary for loop, for-in will inherit the attributes. / method is listed, this needs special attention when using it.

In addition to the traditional for loop, JavaScript defines a for-in method for traversal operations. There are differences in usage depending on the data source.
(1) Traverse objects:

Copy code The code is as follows:

var fish = {
head : 1,
tail : 1,
}
for(var prop in fish) {
console.log(fish[prop]);
}

Observe during debugging: props are 'head', 'tail' in order, that is, when traversing the object properties, they exist in string type, and the loop counter is the property name of the object.
(2) Traverse the array
Copy code The code is as follows:

var arr = [ 'one', 'two', 'three'];
for(var prop in arr) {
console.log(prop);
}

Observe while debugging : prop is '0', '1' in sequence, that is, it still exists in string type when traversing the array. The difference is that the loop counter is the subscript of the array element. (At this time, you can try using a for loop to output, the result is consistent with for-in)
If you add to the code:
Copy the code The code is as follows:

if(Object.prototype.clone === 'undefined')
Object.prototype.clone = function() {};

The output result is: 0,1,clone
If you use a for loop to output, it will still be 0,1; that is to say, the for-in loop will use the attributes of the type of the data source currently operated Traversing out (Similarly, when using for-in on the object fish, clone will also be output), so it is required to pull a string when using for-in to traverse: If you only operate on the object's own attributes, you need to use the inherited attributes Eliminate them, such as using the hasOwnProperty() method.
Statement:
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