Home >Web Front-end >JS Tutorial >Summary of methods for traversing arrays in JavaScript

Summary of methods for traversing arrays in JavaScript

黄舟
黄舟Original
2017-11-09 14:59:151809browse

I believe everyone knows the role of arrays. It manages the storage space of multiple data in batches. Arrays have a long data structure, which can greatly improve the execution efficiency of programs, whether in PHP or ## In #JavaScript or in jQuery, the form of arrays is divided into index arrays and associative arrays, so how to traverse the array! Below we will give you a detailed introduction toJavaScript arrayTraversal~

1.for(){}Traversing the array

<script type="text/javascript">
 <!--
var arr = new Array(13.5,3,4,5,6);
for(var i=0;i<arr.length;i++){
 arr[i] = arr[i]/2.0;
}
alert(arr);
 //-->
 </script>

2.for in loop traverses the array

<html>
<body>
<script type="text/javascript">
var x
var mycars = new Array()
mycars[0] = "Saab"
mycars[1] = "Volvo"
mycars[2] = "BMW"
for (x in mycars)
{
document.write(mycars[x] + "<br />")
}
</script>
</body>
</html>

3.forEach methodNote: the forEach() method is introduced by the ES5.1 standard.

var arr=[1,2,3,4,5,6];
arr.forEach(function(v,i){//v==value 为arr项,i==index 为arr索引
    console.log(i+&#39;  &#39;v );
})//输出0  11  22  33  44  55  6

4. A new method has been added in the latest ES6 standard==for of==

for of method  You can use subscript loops when traversing Array, but you cannot use subscripts when traversing Map and Set. Map, set – no subscript, cannot use index to traverse
In order to unify collection types, the ES6 standard introduces a new iterable type,
Array, Map and Set all belong to iterable types.
==Collections with iterable types can be traversed through the new for ... of loop. ==

var arr=[1,2,3,4,5,6];for(var value of Arr){
    console.log(value);
}  //输出123456

Summary:

The JavaScript method of traversing arrays has been summarized. Do you believe that you are familiar with arrays? We have a certain understanding of traversal , but in our actual development, we still need to choose according to our own needs, because the execution efficiency of some methods is not the best! So use with caution!

Related recommendations:

1.Detailed explanation of the difference between javascript array traversal for and for in

2.php array and js array traversal

The above is the detailed content of Summary of methods for traversing arrays in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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