Home  >  Article  >  Web Front-end  >  Examples of common methods for array traversal in JS

Examples of common methods for array traversal in JS

韦小宝
韦小宝Original
2018-03-14 18:47:481308browse

This article mainly shares with you examples of common methods of JS array traversal. There are three methods in this article. I hope it can help you.

First type: for loop

for(var i=0 , len= arr.length ; i<len ; i++){  代码块 }

Second type: forEach

var arr=[12,14,15,17,18];
var res=arr.forEach(function(item,index,input){
   input[index]=item*10;
});
console.log(res);     //undefined
console.log(arr);     //会对原来的数组产生改变

Parameter description: item: current item in the array

Index: current Index of item

                                                                                                                                                                                                                                                                                        Since the original array input The value has not changed)

var arr=[12,14,15,17,18];
var res=arr.forEach(function(item,index,input){
   return item*10;
});
console.log(res);     //undefined
console.log(arr);     //[12,14,15,17,18]没变

Other instructions: this of the anonymous function points to Windows

If the array is modified in the anonymous function, it will be modified to the

th of the original array Three types: map

var arr=[12,14,15,17,18];
var res=arr.map(function(item,index,input){
    return item*10;
});
console.log(res);    //[120,140,150,170,180]
console.log(arr);    //[12,14,15,17,18]

Parameter description: item: The current item in the array

# Important note: There is a return value (if no return value is given, res is undefined, but res is indeed an array. As long as the input is changed, the original array will change)

var arr=[12,14,15,17,18];
var res=arr.map(function(item,index,input){
   input[index]=item*10;
});
console.log(res);     //[undefined, undefined, undefined, undefined, undefined]
console.log(arr);     //[120,140,150,170,180]

Other notes: Anonymous functions this points to Windows


If the array is modified in the anonymous function, it will be modified to the original array

The above is the detailed content of Examples of common methods for array traversal in JS. 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