ES5 a lot of new things to know about our writing JavaScript will be a lot of help, such as the array of this piece, we may not need to rhythmic to for
the loop.
ES5 new Write array method, such as foreach (JS v1.6), map (JS v1.6), filter (JS v1.6), some (JS v1.6), every (JS v1.6), indexOf (JS v1.6), Lastinde XOf (JS v1.6), reduce (JS v1.8), Reduceright (JS v1.8)
- ForEach
forEach
Is the most basic of the new array method, that is, traversal, loop. For example, the following example:[1, 2, 3, 4] . ForEach (alert);
This is equivalent to the following traditional for
loop:
Array = [4]; for (Array.Length; k < length; k++) {alert (array[k]);}
Array in ES5 new method, the parameters are all types, the default is the parameter function
, which are the parameters? See below:
[2,4]. ForEach (Console.log); //Results://1, 0, [1, 2, 3, 4]//2, 1, [1, 2, 3, 4]//3, 2, [1, 2, 3, 4]//4, 3, [1, 2,3, 4] /c20>
Obviously, forEach
the callback in the method function
supports 3 parameters, the 1th is the array contents of the traversal, the 2nd is the corresponding array index, and the 3rd is the array itself.
Therefore, we have:
[].foreach (function (value, index, array) { //...});
Compare the methods in jquery $.each
:
$.each ([], function (index, value, array) { //...});
Will find that the 1th and 2nd parameters are exactly the opposite, we have to pay attention to, do not remember the wrong. A similar approach is followed, for example $.map
.
Now, we can use forEach
a slightly more complete example of showing off, array summation:
var sum = 0;[ 1, 2, 3, 4]. ForEach (function (item, index, array) {console. Log (array[index] = = item); //true sum + = ITEM;}); alert (sum); //10
Further down, further, forEach
in addition to accepting a mandatory callback function parameter, you can also accept an optional context parameter (change the pointer inside the callback function this
) (the 2nd parameter).
Array.foreach (callback,[Thisobject])
Examples are more illustrative of everything:
var database = { users: ["Zhang Yun", "Dancing Dogs", "Li Xiaolu"], sendemail:function (user) { if (this.isvaliduser (user)) {
console.log ("Hello," + user); } else { Console.log ("Sorry," + user + ", you are not a family member")} , isvaliduser:function (user) { return/^/. Test (user); }};/ /Give everyone legal mail Database.users.forEach (/
/database.users in person traverse Database.sendemail, //Send mail Database //Use database in place of the above marked red); Results://Hello, Zhang Han Yun//Sorry, dancing dogs, you are not the family//Sorry, Li Xiaolu, you are not a clan
If this 2nd optional parameter is not specified, the global object is used instead (in the case of the browser window
), or even in strict mode undefined
.
In addition, foreach does not traverse the purely "official rates" element, such as the following example:
Array = [array[//Remove 2alert (//"1,,3" alert (//But the length is still 3array. ) Just 1 and 3 pop up.
- Map
Here'smap
Not the meaning of "map", but "mapping".[].map();
Basic usage andforEach
Similar methods:Array.map (callback,[thisobject]);
callback
The parameters are similar:
[].map (function (value, index, array) { //...});
map
The function of the method is not difficult to understand, "mapping", that is, the original array is "mapped" into a corresponding new array. The following example is the value of the square:
var data = [1, 2, 3, 4];var arrayofsquares = Data.map (function (item) { //1, 4, 9,
callback
Need to have a return
value, if not, just like this:
var data = [1, 2, 3, 4];var arrayofsquares = Data.map (function () {}); Arrayofsquares.foreach (Console.log);
As a result, as you can see, all the items in the array are mapped undefined
:
In practical use, we can make use of the map
method to obtain the specific attribute values in the object array conveniently. For example, the following example is also the example of a compatible demo:
var users = [ {name: "Zhang contains rhyme", "email": "[email protected]"}, {name: "Dancing Dogs", "email": "[email protected]"}, {name: "Li Xiaolu", //[email protected], [email protected], [email protected]
- filter
filter
is the meaning of "filter", "Filter". After the index group filter
, the new filtered array is returned. Usage is very similar to map
:
array.filter (callback,[thisobject]);
The filter
's callback
function needs to return a Boolean value of true
or false
. If true
It means, through! If false
,
may be in doubt, must it be a boolean
value? We can simply test the following, as follows:
var data = [0, 1, 2, 3];var arrayfilter = Data.filter (function (item) {return item;}); Console.log (Arrayfilter); //[1, 2, 3]
The has this visibility, as long as the return value is weak equals = = True/false
on it, rather than having to return = = = True/false
.
- Some
some
meaning "certain" refers to whether "certain items" are eligible. With the following is a every
good friend, every
said whether "every" should be reliable. Use the following:Array.some (callback,[thisobject]);
For example, the following simple use:
var scores = [5, 8, 3, 10];var current = 7;function Higherthancurrent (score) { return score > current;} if (Scores.some (higherthancurrent)) { alert ("I've got it!") ");}
The result pops up the "I Quasi" text. some
requires at least 1 values for callback
the return true
to be allowed. Obviously, 8 > 7
so the scores.some(higherThanCurrent)
value is true
.
We can naturally use the forEach
judgment, however, compared some
to the lack of, only the return is some
true
no longer executed.
- Every
some
the relationship with the basic friend is already a public secret, but also return a Boolean value, but every
need every concubine to let me satisfied, otherwise-"bearer, dragged me out to chop!" ”The result is:
- IndexOf
indexOf
The method is in the string since ancient times, string.indexOf(searchString, position)
. The array here is similar to the indexOf
method.Array.indexof (searchelement[, FromIndex])
Returns an integer index value, if no match (strict match) is returned -1
. fromIndex
Optional, means to start the search from this location, if the default or format is not required, using the default values 0
, I test under Firefox, I found that the use of string values is also possible, for example, "3"
and 3
can be.
-1 (not found because 5!== "5")
For IETester IE6:
- lastIndexOf
lastIndexOf
Method andindexOf
Similar methods:Array.lastindexof (searchelement[, FromIndex])
Just lastIndexOf
start looking at the end of the string, not from the beginning. Another difference is that fromIndex
the default value is array.length - 1
not 0
.
IE6 and other browsers are tossing:
if (typeof Array.prototype.lastIndexOf! = "function") { Array.prototype.lastIndexOf = function (Searchelement, FromIndex) { var index =-1, length = this.length; FromIndex = fromIndex * 1 | | length-1; for (var k = length-1; k >-1; k-=1) { if (k <= fromIndex && this[k] = = = searchelement) { index = K; break; } } return index; };}
Thus, there are:
-1 (not found)
- Reduce
reduce
is introduced in JavaScript 1.8, Chinese meaning "reduction", "reduced". However, from a functional point of view, I personally can not be associated with the meaning of "reduction", but closer to the "iteration", "recursion (recursion)", rub, because the word is so close, will not be ECMA-262 5th the writer error is wrong ~ ~This method is more complex than the above methods and is used as follows:
Array.reduce (callback[, InitialValue])
callback
The function accepts 4 parameters: the previous value, the current value, the index value, and the array itself. initialValue
The parameter is optional and represents the initial value. If specified, it is treated as the originally used value, and previous
if the default, the first element of the array is used as the previous
initial value, and the back row is current
one initialValue
less iteration than the value.
var sum = [1, 2, 3, 4].reduce (function (Previous, current, index, array) { //
Description
- Because
initialValue
it does not exist, the previous
first value is equal to the initial element of the array.
- Thus the
current
value is at the time of the first call 2
.
- The last two parameters are index values
index
and the array itself array
.
The following is the loop execution process:
Initial Setup previous = InitialValue = 1, current = 2//First Iteration previous = (1 + 2) = 3, current = 3//second Iteration previous = (3 + 3) = 6, current = 4//Third Iteration previous = (6 + 4) = Ten, current = undefined (exit)
With this reduce
, we can easily achieve flattening of two-dimensional arrays:
var matrix = [ [1, 2], [3, 4], [5, 6]]; Two-dimensional array flattening var flatten = matrix.reduce (function (Previous, current) { //[1, 2, 3, 4, 5, 6]
Compatible processing IE6-IE8:
if (typeof Array.prototype.reduce! = "function") { Array.prototype.reduce = function (callback, initialvalue) { var previous = InitialValue, k = 0, length = this.length; if (typeof InitialValue = = = = "undefined") { previous = this[0]; k = 1; } if (typeof callback = = = "function") {for (k; k < length; k++) { this.hasownproperty (k) && (previous = Callback (Previous, This[k], K, this)); } } return previous;} ;}
Then, test the integration, demo demo, you can click here: IE6-compatible reduce method test Demo
IE6 browser results such as:
- Reduceright
reduceRight
Withreduce
In comparison, the usage is similar:Array.reduceright (callback[, InitialValue])
The difference in implementation reduceRight
is that it is implemented from the end of the array. Look at the following example:
var data = [1, 2, 3, 4];var Specialdiff = data.reduceright (function (Previous, current, index) { if (index = = 0) {
return previous + current; }
//0
0
How did the results get?
We take a step-by-step look at Loop execution:
Initial setting index = 3, previous = InitialValue = 4, current = 3//First Iteration index = 2, previous = (4-3) = 1, current = 2// Second iteration index = 1, previous = (1-2) =-1, current = 1//Third Iteration index = 0, previous = ( -1 + 1) = 0, current = undefined (fallback Out)
For the low-version browser to support this method, you can add the following code:
if (typeof Array.prototype.reduceRight! = "function") { Array.prototype.reduceRight = function (callback, InitialValue) { var length = this.length, k = length-1, previous = InitialValue; if (typeof InitialValue = = = = "undefined") { previous = this[length-1]; k--; } if (typeof callback = = = "function") {for (k; k >-1; k-=1) { this.hasownproperty (k) && (previous = cal Lback (Previous, This[k], K, this)); } } return previous;} ;}
You can click here: Reduceright easy to use demo
Compare the results under the Firefox browser and the IE7 browser:
We can also apply the above array methods to other objects.
For example, we use foreach to traverse DOM elements.
And so many other class array applications.
Above for reprint, from Zhang Xin Xu-Xin space-Xin Life [http://www.zhangxinxu.com]