5 common methods for array arrays

Source: Internet
Author: User
Tags pear

ES6 era is coming, do not know es5 you are familiar with it?

Here is an introduction I used to 5 methods, the evil IE9 do not support, need to do compatible with caution

IndexOf

The IndexOf () method returns the position of the first element found in the array, or 1 if it does not exist.

eg

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

When we don't use it, it's like this.

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

It is obvious that the code volume has increased significantly.

Has the advantage has the flaw, that is the evil ie, IE9 does not support this method.

2) Filter

The filter () method creates an array of new matching filter conditions.

eg

Ar 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);

  

Compare

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);

3) ForEach ()

foreach executes the corresponding method for each element

eg

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++) {      consol E.log (Arr[i]);} Console.log ("========================");//uses ForEach to Iteratearr.foreach (function (item,index) {      Console.log (item);});

Compare

foreach is used to replace a for loop

4) Map ()

Map () A new array is returned after each element of the array is manipulated (mapped)

eg

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 ());

Compare

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 ());

Map () is a very useful function when processing a server to return data.

5) reduce () reduce () can implement the function of an accumulator, reducing each value (from left to right) of the array to a value. To tell the truth, it's a little difficult to understand this sentence, it's too abstract. Scene: Count the number of distinct words in an array

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 ());

Compare

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 ());

  

Let me first explain my own understanding of reduce. Reduce (callback, InitialValue) passes two variables. The callback function (callback) and the initial value (InitialValue). Suppose the function has an incoming parameter, prev and Next,index, and an array. Prev and next you have to understand. 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 Initivalvalue,next will be the first element in the array.
/** the difference between the two, run it in the console to 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 ());

Re-introduce another article (compatible processing)

http://www.dengzhr.com/js/362

5 common methods for array arrays

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.