A number of methods for manipulating arrays have been added to the ES5 specification and are hereby listed for use
1. Foreach Loop
A bit like the Each loop of jquery
[12,23,36,4,5].foreach (function (v,k) {
Console.log (v) Gets the element value, 12,23,36,4,5
Console.log (k) Gets the element subscript, 0,1,2,3,4
})
Easy to traverse various arrays without the help of a three-party library
2.filter Filter
Used to filter elements
var arr = [12,23,36,4,5].filter (function (x) {
Return x>10; At this point, elements greater than 10 are filtered and placed into a new array, and the array is returned after the function ends
});
Console.log (arr) get [12,23,36]
3.every Matching
Similar to the format of the filter above, but returns a bool value
Returns true if all elements in the array are filtered, otherwise false
4.some Matching
Relative to the every, as long as one element passes the filter and returns True, NONE returns False
5.reduce Combination
Combine elements within an array to perform related operations
For example, an array summation
var sum = [12,23,36,4,5].reduce (function (x, y) {
return x+y;
},0);
Final sum gets the sum in the array
Basically receive a function to return the corresponding combination operation, and then you can set the initial value of the return value, where the sum initial value is 0
Two more examples to help understand
Array quadrature
var ji = [12,23,36,4,5].reduce (function (x, y) {
return x*y;
},1);
Obviously, the default initial value is 1 instead of 0.
To find the maximum value
var max = [12,23,36,4,5].reduce (function (x, y) {
Return (x>y)? x:y;
});
The maximum value does not require an initial value, and returns the maximum value obtained after 22 comparison
6.reduceRight
and reduce usage are basically the same, the difference is that all operations are from right to left, and in certain priority situations there will be different
Some ES5 methods for manipulating arrays