The ECMAScript5 standard was released on December 3, 2009, and it brings some new ways to improve existing Array array operations. However, these novel array methods did not really become popular because there was a lack of ES5-enabled browsers on the market at that time.
Array "Extras"
No one doubts about the practicality of these methods, but writing polyfill (PS: plugin compatible with older browsers) is not worth it for them. It turns "must implement" into "best implement". Some people actually call these array methods Array "Extras". Why!
But times are changing. If you look at the popular open source JS projects on Github, you will see that the trend is changing. Everyone wants to cut down a lot of dependencies (third-party libraries) and implement them with only local code.
OK, let's get started.
My 5 arrays
In ES5, there are 9 Array methods in total http://kangax.github.io/compat-table/es5/
Note* Nine methods
Array.prototype.indexOf
Array.prototype.lastIndexOf
Array.prototype.every
Array.prototype.some
Array.prototype.forEach
Array.prototype.map
Array.prototype.filter
Array.prototype.reduce
Array.prototype.reduceRight
I will choose 5 methods, which I personally think are the most useful and many developers will encounter.
1) indexOf
The indexOf() method returns the position of the first element found in the array, and -1 if it does not exist.
When indexOf is not used
var arr = ['apple','orange','pear'],found = false;for(var i= 0, l = arr.length; i< l; i++){if(arr[i] === 'orange'){found = true;}}console.log("found:",found);After use
var arr = ['apple','orange','pear'];console.log("found:", arr.indexOf("orange") != -1);2) filter
The filter() method creates a new array matching the filter criteria.
When filter() is not used
var arr = [ {"name":"apple", "count": 2}, {"name":"orange", "count": 5}, {"name":"pear", "count": 3}, {"name":"orange", "count": 16},]; var newArr = [];for(var i= 0, l = arr.length; i< l; i++){ if(arr[i].name === "orange" ){newArr.push(arr[i]);}}console.log("Filter results:",newArr);Use filter():
var arr = [ {"name":"apple", "count": 2}, {"name":"orange", "count": 5}, {"name":"pear", "count": 3}, {"name":"orange", "count": 16},]; var newArr = arr.filter(function(item){ return item.name === "orange";});console.log("Filter results:",newArr);3) forEach()
forEach executes the corresponding method for each element
var arr = [1,2,3,4,5,6,7,8];// Uses the usual "for" loop to iteratefor(var i= 0, l = arr.length; i< l; i++){console.log(arr[i]);}console.log("========================");//Uses forEach to iteratearr.forEach(function(item,index){console.log(item);});forEach is used to replace the for loop
4) map()
After map() performs a certain operation (map) on each element of the array, a new array will be returned.
Don't use map
var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}];function getNewArr(){ var newArr = []; for(var i= 0, l = oldArr.length; i< l; i++){ var item = oldArr[i]; item.full_name = [item.first_name,item.last_name].join("); newArr[i] = item; } return newArr;}console.log(getNewArr());After using map
var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}]; function getNewArr(){ return oldArr.map(function(item,index){ item.full_name = [item.first_name,item.last_name].join(" "); return item; }); }console.log(getNewArr());map() is a very practical function when processing data returned by the server.
5) reduce()
reduce() can implement the function of an accumulator, reducing each value of the array (from left to right) to a value.
To be honest, it was a bit difficult to understand this sentence at the beginning, it was too abstract.
Scenario: Statistics how many unrepeatable words are in an array
When not using reduce
var arr = ["apple","orange","apple","orange","pear","orange"];function getWordCnt(){ var obj = {}; for(var i= 0, l = arr.length; i< l; i++){ var item = arr[i]; obj[item] = (obj[item] +1 ) || 1; } return obj;}console.log(getWordCnt());After using reduce()
var arr = ["apple","orange","apple","orange","pear","orange"];function getWordCnt(){ return arr.reduce(function(prev,next){ prev[next] = (prev[next] + 1) || 1; return prev; },{});}console.log(getWordCnt());Let me explain my own understanding of reduce first. reduce(callback, initialValue) will pass in two variables. Callback function (callback) and initialValue. Suppose the function has an incoming parameter, prev and next, index and array. You must understand prev and next.
Generally speaking, prev starts with the first element in the array, and next is the second element. But when you pass in the initial value (initialValue), the first prev will be initialValue, and next will be the first element in the array.
for example:
/** The difference between the two, run it in the console and you will know */var arr = ["apple","orange"];function noPassValue(){ return arr.reduce(function(prev,next){ console.log("prev:",prev); console.log("next:",next); return prev + " " +next; });}function passValue(){ return arr.reduce(function(prev,next){ console.log("prev:",prev); console.log("next:",next); prev[next] = 1; return prev; },{});}console.log("No Additional parameter:",noPassValue());console.log("----------------");console.log("With {} as an additional parameter:",passValue());