5 well-worth-to-use array methods in "translation" javascript

Source: Internet
Author: User
Tags pear

Original address : http://colintoh.com/blog/5-array-methods-that-you-should-use-today?utm_source=javascriptweekly &utm_medium=email

Since the formal specification was defined in October 2009 ECMAScript 5, some array methods have been proposed to improve productivity. However, these methods are not widely used by developers because of ES5 's poor browser support rate.

"Redundant" Array method

No one will question the usability of these methods, but if you write Polyfill for them (about Polyfill, personal understanding is that the browser "plugin" or extension, which is written to make the new method compatible with each browser, can refer to this article) is not worth it. Therefore, these new methods are considered "good-to-have" rather than "must-have", or simply called "superfluous" methods. ouch!

But with the development of front-end technology today, if you're constantly looking at some of the popular open source JS projects on GitHub, you'll see a trend: Developers are increasingly inclined to use native code instead of relying on third-party libraries.

Therefore, it is necessary to promote the widespread use of native grammar.

5 Interesting Array methods

Below, I will introduce the very useful 5 array methods in ES 5, which can improve the productivity of the developer.

1. IndexOF

The IndexOf method returns the index value of an element in the array and returns 1 if the element does not exist in the array.

Take a chestnut: check the position of "orange" in the array

(1) Do not use indexof ()

var arr = [' Apple ', ' orange ', ' pear '],    false;  for (var i= 0, L = arr.length; i< l; i++) {    if(arr[i] = = = ' Orange ') {         C14>true;}    } Console.log ("found:", found);

(2) using indexof ()

var arr = [' Apple ', ' orange ', ' pear '];console.log ("Found:", Arr.indexof ("orange")! =-1);

The code is a lot simpler!

Now I have a new requirement: I want to know all the elements in the array that match the given criteria. What to do?

2. Filter

The filter () method creates a new array of all elements in the specified array that match the given criteria

Give me a chestnut: find all the elements of the array named "Orange"

(1) without filter ()

var arr = [    {"name": "Apple", "Count": 2},    {"name": "Orange", "Count": 5},    { "name": "Pear", "Count": 3},    {"name": "Orange", "count": +},];     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);

(2) Use filter ()

var arr = [    {"name": "Apple", "Count": 2},    {"name": "Orange", "Count": 5},    { "name": "Pear", "Count": 3},    {"name": "Orange", "count": +},];     var newArr = Arr.filter (function(item) {    return Item.name = = = = " Orange ";}); Console.log ("Filter results:", NEWARR);

The code is a lot simpler.

3. foreach ()

The foreach () method executes the given method one time for each element in the array

For a chestnut: comparison of the For Loop and the foreach () method

function Test () {    var arr = [1,2,3,4,5,6,7,8];     // Uses the usual ' for ' loop to iterate     for (var i= 0, L = arr.length; i< l; i++) {        console.log (arr[i]);    }    Console.log ("========================");     // Uses ForEach to iterate    Arr.foreach (function(item,index) {        console.log (item);    });}

The foreach () method is an upgrade notation for a for loop. I recommend that you try to use the foreach () method if you can choose.

There is an easily overlooked problem with the FOR loop: variables declared in the For loop (such as Var i=0 in the previous example) are not local variables in the for loop, but local variables within the scope of the For loop. in the example above, the variable var i = 0 declared in the for loop is actually a local variable within the scope of the method test (), and I can easily be accessed and rewritten by other logic within the scope of the test (), causing some problems.

In fact, tests by Jsperf show that the For loop has a much better performance than foreach ().

However, I personally always believe that the foreach () method is still adhered to unless you are dealing with big data above millions. millisecond-saving time is not a major consideration for improving product performance.

4. Map ()

Calls the defined callback function for each element of the array and returns an array containing the result

For a chestnut: Parses an array, adds a FullName property to each element in the array, and returns a new array

(1) Do not 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.first_name,item.last_name].join ("");         = item;    }         return NEWARR;} Console.log (Getnewarr ());

(2) 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.first_ Name,item.last_name].join ("");         return item;    });    } Console.log (Getnewarr ());

The map () method works well in heavy-duty JavaScript applications that contain server data interactions.

5. Reduce ()

invokes the specified callback function for all elements in the array. The return value of the callback function is the cumulative result, and this return value is supplied as a parameter the next time the callback function is called

To be honest, I have weighed it for a long time before using reduce (). The concept of reduce () is very abstract to me, especially the word "accumulate". The concept of reduce () is not gradually mastered until a series of JavaScript methods have been learned in Nodeschool. But I still haven't found out how much it works until one day I was refactoring my code and found out that reduce () was a blast!

For a chestnut: parses an array and returns an object containing the number of occurrences of each element in the array

(1) without 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] +1) | | 1;    }         return obj;} Console.log (getwordcnt ());

(2) using reduce ()

var arr = ["Apple", "orange", "apple", "orange", "pear", "orange"]; function getwordcnt () {    return arr.reduce (function(prev,next) {        = (Prev[next] + 1 ) || 1;         return prev;    },{});} Console.log (getwordcnt ());

I'll explain the personal understanding of reduce () below.

reduce (Callback,initialvalue) has two parameters, callback functions, and InitialValue. Where the callback function consists of 4 parameters: Prev,next,index and array. We generally only need to use the Prev and next two parameters.

The prev parameter represents the first element in the array, and next represents the second element in the array. Note: If the InitialValue parameter is set, Prev represents InitialValue, and next represents the first element in the array. For example, in the example above. InitialValue is set to a blank object {}, then Prev is {}.

/** Difference between not passing no parameters* and passing in a additional parameter into ' reduce () '*/vararr = ["Apple", "orange"];functionNopassvalue () {returnArr.reduce (function(Prev,next) {Console.log ("Prev:", prev); Console.log ("Next:", next); returnPrev + "" +Next; });}functionPassvalue () {returnArr.reduce (function(Prev,next) {Console.log ("Prev:", prev); Console.log ("Next:", next); Prev[next]= 1; returnprev; },{});} Console.log ("No Additional parameter:", Nopassvalue ()); Console.log ("----------------"); Console.log ("With {} as an additional parameter:", Passvalue ());

In the preceding code, each iteration returns a value that is passed in as the prev parameter of the next iteration.

The following code will show the functionality of reduce () more clearly:

vararr = ["Apple", "orange", "apple", "pear"];functiongetwordcnt () {returnArr.reduce (function(Prev,next,index) {Console.log ("<b>iteration" +index+ "</b>"); Console.log ("Prev:", prev); Console.log ("Next:", next); Prev[next]= ++prev[next] | | 1; Console.log ("Passing this to the ' prev ' of the next iteration if any:", prev); Console.log ("---------------"); returnprev; },{});} Console.log ("<b>final object:</b>", getwordcnt ());

Demethodizing

Although the above mentioned methods are only for arrays, they can be used by node lists, jquery objects, and even strings. We can extend these array methods through a "demethodizing" technique.

// demethodizing The Array method, ForEach (), into  a generic ' each 'var each = function.prototype. Call.bind ([].foreach); var nodeList = Document.queryselectorall ("P"); each (nodelist,bold); function Bold (node) {   = "bold";}

We extend the Foreach method to each method of the Function class through Function.prototype.call.bind , and now each method can be used by objects other than the array.

Browser support degree

According to ECMAScript 5 compatibility table, the above 5 methods can be used in all mobile browsers and almost all desktop browsers (when I say "all", IE9 the following browsers please consciously leave).

5 well-worth-to-use array methods in "translation" javascript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.