The array method in ECMAScript 5 and the ecmascript Array Method
1. forEach ()
The forEach () method traverses the array from the beginning to the end and calls the specified function for each element.
Var data = [1, 2, 3, 4, 5]; var sum = 0; data. forEach (functiion (value) {sum + = value}) // accumulate each value to sum
2. map ()
The map () method passes each element of the Call Amount array to the specified function and returns an array containing the return value of the function.
a=[1,2,3];b=a.map(function(x){return x*x})
3. filter ()
The array element returned by the filter () method is a subset of the called array. Literally, it means filtering.
A = [5, 4, 3, 2, 1]
Smallvalues = a. filter (function (x) {return x <3}) // [2, 1]
Everyother = a. filter (function (x, I) {return I % 2 = 0}) // [5, 3, 1]
4. every () and some ()
The every () and some () methods are logical judgments of arrays. They are used to evaluate the specified functions of array elements and return true or false.
a=[1,2,3,4,5]a.every(function(x){return <10})//truea.every(function(x){return x%2==0})//false
5. reduce and reduceRight
The reduce and reduceRight methods use the specified function to combine array elements to generate a single value. The second parameter is an initial value passed to the function.
Var a = [1, 2, 3, 4, 5] var sum =. reduce (function (x, y) {return x + y}, 0) // The sum of arrays is 1 + 2 + 3 + 4 + 5var product =. reduce (function (x, y) {return x * y}, 1) // The array calculates the product 1*2*3*4 * 5var max =. reduce (function (x, y) {return (x> y )? X: y}) // calculates the maximum value.
The working principle of reduceRight () is the same as that of reduce (). The difference is that it processes data from high to low according to the array index, rather than from low to high.
5. indexOf and lastIndexOf ()
IndexOf () and lastIndexOf () Search for elements with Given Values in the entire array, and return the index of the first element found. If no value is found,-1 is returned.
This function does not need to be described too much ~