forEach JavaScript array of applications, map, filter, reduce

JavaScript array of methods to explain

 

The method ES5.0 ES3.0 methods respectively:

  1. Change the original array: reverse, sort, push, pop, unshift, shift, splice
  2. Source array can not be changed: the operation does not change the original array, the array may be changed using the extracted : forEach, filter, Map, the reduce, reduceRight, Slice, the concat, the Join, -> Split, toString

A, Push may receive any number of parameters, to add them to the end of the array by one, and returns the length of the array is modified.

Push to achieve an array: on the prototype chain all contribute to an array of programming called directly without the need to call a function to use.

Array.prototype.push = function () {

var len = arguments.length;

for(var i = 0; i < len; i ++){

this[this.length] = arguments[i];

}

return this.length;

}

pop: removing the last one end of the array, reducing the length of the array of values, and then returns the item removed

shift (): Delete the original first array, and returns the value of the removed element; empty array returns undefined 

unshift: add parameters to the beginning of the original array, and returns the length of the array.

sort (): ascending order array entry - i.e., the minimum value is located in the front, the maximum value at the bottom surface. Provides an interface for people to define their own function function you want.

Method sort -> provides interface functions

1, two parameters must

2, see the return value 1) when the value is negative then the number of returns in front of the front

2) a positive number, the number in front of the latter

3) is 0, fixed

arr.sort(function (a, b) {

// return ab; // ascending

// return ba; Descending

return  . the Math Random () -  0.5 ; // random ordering

});

S plice: very powerful array of methods, there are many uses it can be achieved delete, insert and replace. splice (several starting position, to be deleted, [number to be inserted (-s)])

two,

 C oncat: add parameters to the original array. This method will create a copy of the current array, and then add the received parameter to the end of this copy, and finally returns an array of newly constructed

T Ostring: will be preached parameters into a string

S lice: Returns the index into the start end of the original index from the array ( excluding the ending superscript ) a new array of items between. slice () method can accept one or two parameters, i.e., to return to the start and end position of the item.

J OIN: the Join (separator): the array element from the group of a string , as the separator in the separator, is omitted, the default is a comma separator, which receives only one parameter: the separator.

S Plit: Split (separator): a string split into an array , in a separator as a separator, which receives only one parameter: the separator.

These methods ES3.0 is an array of

The new method ES5.0 you have the following methods:

. 1, forEach: array traverse cycle of operation of each item in the array to a given function. This method has no return value. Type function parameters are the default parameters have passed, the parameters are: an array of content traverse; corresponding to the index of the first array, the array itself.

Define an array to facilitate subsequent calls to the various methods of Examples;

was arr = [

{Name: "Liu Fei", des: 'cervical bad', sex: 'm', age: 23},

{Name: 'LiuYingJian', des: 'Eucharist good', sex: 'f', age: 19},

{Name: 'Wang Shu', des: 'No Eucharist', sex: 'f', age: 20},

{Name: 'Lei Wang', des: 'man you have not seen', sex: 'm', age: 21},

{Name: 'Liu Lang', des: 'very skin', sex: 'm', age: 22}

];

A transfer function parameter must func (ele each element, index index bit, Self itself), the second pass may not pass this point can not pass the point when the window function is executed

var oLiArray = document.getElementsByTagName('li');

arr.forEach(function(ele, index, self) {

this[index].innerText = ele.name;

}, oLiArray)

Output:

The result is an array of preaching every turn call this function, to achieve a certain function of the array (this example is in the array to be inserted into each of the li)

Of course, we can rewrite it to achieve the same functionality: easy programming of course, be used directly in the prototype chain array array

Array.prototype.myForEach = function (func) {

// you can pass two parameters, and this function (pointing function during use), to receive this with parma2

// _ arr call to receive current array (who call on who point)

var _arr = this, len = _arr.length, parma2 = arguments[1] || window;

for (var i = 0; i <len; i ++) {

func.apply(parma2, [_arr[i], i, _arr]);

}

}

Re-calls can get more results.

filter: Filter ", each array running a given function, returns the array of the filter condition.

eg:

var newArr = arr.filter(function(ele, index, self) {

if(ele.sex == 'm')

return true;

});

Results;

Inside the function to determine true or false, if true the current item is returned, otherwise filter out the current item.

Rewrite it:

Array.prototype.myFilter = function (func) {

// define a new addition to receiving the last empty array and returns the results

var _arr = this, len = _arr.length; parma2 = arguments[1] || window, newArr = [];

for (var i = 0; i <len; i ++) {

func.apply(parma2, [_arr[i], i, _arr]) ? newArr.push(deepClone({}, _arr[i])) : '';

}

return newArr;

}

M the AP: refers to the "mapping" of each item in the array run the given function, each function call returns the result of an array.

If X --------------- + 10 ---------> Y i.e. have increased each X 10 is then sent to a different array of mappings between

Instructions:

var newArr = arr.map(function(ele, index, self) {

ele.name += 10;

return ele; or each return of the original //

})

The results are:

 

Rewrite:

Array.prototype.myMap = function(func) {

var _arr = this, len = _arr.length, parma2 = arguments[1] || window, newArr = [];

for (var i = 0; i <len; i ++) {

newArr.push (deepClone ({}, func.apply (parma2, [_arr [i], i, _arr]))); // clone using the depth does not affect the original array

}

return newArr; // returns a new array accepted

}

R & lt educe the and reduceRight: the reduce () method from the first item in the array, traversed by one end, then from right to left traversal reduceRight. Function passed to reduce () and reduceRight () received four parameters: the previous value, the current value of the index, and an array of object entry. Any value returned by this function will be automatically passed to the next one as the first parameter. Occurs on the first iteration of the second array, so the first item in the array is the first parameter, the second parameter is the second item in the array.

Instructions:

var initialValue = {name: '22'};

var lastValue = arr.reduce(function(preValue, curValue, index, self) {

preValue.name += 1;

return preValue

}, initialValue);

Result of the call:

Plus one each from left to right, the result is not the last call as the lower accumulating time;

Rewriting can be achieved:

Array.prototype.myReduce = function (func, initialValue) {// Here pass two parameters must, of course, the second and third parameters as above may not be available for transmission

var _arr = this, len = _arr.length, parma2 = arguments[2];

for (var i = 0; i <len; i ++) {

initialValue = func.apply(parma2, [initialValue, _arr[i], i, _arr]);

}

return initialValue;

}

Application: a string and separated into an array in its entirety, its attributes and values ​​of the number of the original string:

eg:

var cookie = "1=a;2=b;3=c;4=d;5=e;6=f;7=g";

function parseCookie(str) {

var cookieArr = str.split(";");

was cookObj = {};

cookieArr.reduce(function(pre, next, index, self){

var nextArr = next.split('=');

cookObj[nextArr[0]] = nextArr[1];

return pre;

} Chokobj)

return cookObj;

}

var cook = parseCookie(cookie);

console.log(cook);

 

Output:

Although the method is difficult to reduce a little difficult but it is still a good use;

every Method: Analyzing the array is not in line with each of the requirements if it returns false (corresponding &&)

some method of: determining the presence of the array is not a satisfactory one, if it returns true. (Equivalent to ||)

var flag = arr.every(function(ele, index, self) {

return ele.age > 20;

});

var flag1 = arr.some(function(ele, index, self) {

return ele.age > 20;

});

Output

 

Rewrite it:

Array.prototype.myEvery = function(func) {

// Add a variable determination facilitate return true

var _arr = this, len = _arr.length; parma2 = arguments[1] || window, flag = true;

for (var i = 0; i <len; i ++) {

if(!func.apply(parma2, [_arr[i], i, _arr])){

flag = false;

}

}

return flag;

}

some similar method

 

 

The main purpose is to rewrite so that we can better understand the underlying principles, easy to use

It need not be very dependent on other people's methods to increase the autonomy

 

The above is an array of methods commonly used in JavaScript. Thank you to adopt, the proposed write their own

Published 19 original articles · won praise 58 · views 50000 +

Guess you like

Origin blog.csdn.net/cyg_l02/article/details/82286432