1. Common methods of JavaScript arrays

1. Basic method:
push: add an item to the end of the array and the return value is the new length of
the array unshift: add an item to the beginning of the array and the return value is the new length of the array
pop: delete the end item of the array and the return value is the deleted array item
shift: delete the beginning item of the array and return the deleted beginning item
splice: add, delete, modify, powerful
slice: the return value of the copied array is the new array copied to the new array after the value is written, and does not include the last item to be copied

2. Concatenation:
concat: concatenate an array with another array to return the concatenated array 
join: concatenate each item in the array into a string according to the specified delimiter

3. Sort:
reverse: reverse array return value reverse array original array change
sort: bubble sort according to anonymous function ba reverse ab ascending

4. Poor compatibility:
indexOf: returns the index of the acquired item in the array
lastIndexOf: returns the last index of the acquired item in the array
forEach: loops through the array parameter is an anonymous function and returns undefined by default
map: loops through the array parameter is an anonymous function
filter: creates a new array that matches the filter conditions
reduce: each value in the array (from left to right) starts to merge and ends up being a single value.

1. Basic method:

push : add an item to the end of the array and the return value is the new length of the array
unshift : add an item to the beginning of the array and the return value is the new length of the array

var array = ["a","b","c","d","e","f"];
var last = array.unshift("begin");
console.log(array)     // ["begin", "a", "b", "c", "d", "e", "f"]

 

pop : delete the end item of the array and the return value is the deleted array item

var array = ["a","b","c","d","e","f"];
var last = array.pop();
console.log(array)    //["a", "b", "c", "d", "e"]

 

shift : delete the beginning item of the array and return the deleted beginning item

var array = ["a","b","c","d","e","f"];
var last = array.shift();
console.log(array)      // ["b", "c", "d", "e", "f"]

 

splice : additions, deletions and modifications, powerful

(1 ) Delete: only need to provide two parameters, the position of the first item to be deleted and the number to be deleted, and return the deleted element array:
 var num = [1,2,3,4,5 ];
 var newNum = num.splice(1,2 );
console.log(num);     // [1,4,5] 
console.log(newNum); // [2,3] 

( 2 ) Insert: provide multiple parameters, the first parameter is the position to insert, The second is 0 to delete 0, followed by the element to be inserted, which can be multiple, because 0 is deleted, so an empty array is returned;
 * Four parameters, the second is 0 to insert
var
num = [1, 2,3,4,5 ]; var newNum = num.splice(1,0,"Tom","Jerry" ); console.log(num); // [1, "Tom", "Jerry", 2, 3, 4, 5] console.log(newNum); // [] ( 3 ) replace: provide multiple parameters, the first One parameter is the position to be inserted, the second is the number of deletions, followed by the elements to be inserted, which can be multiple, and returns the deleted array;
* Four parameters, the second is greater than 0 to represent replacement, what is the number Indicates how much to replace, the first parameter represents the number of places to replace from the subscript
var num = [1,2,3,4,5 ]; var newNum = num.splice(1,2,"Tom","Jerry " ); console.log(num); //[1, "Tom", "Jerry", 4, 5] console.log(newNum); //[2,3]

 

slice : The return value of the copied array is the new array copied to, this method does not modify the original array

    * Returns a new array containing the elements in arrayObject from start to end (excluding this element).

    * If end is not specified, the slice() method selects all elements from start to the end of the array.

var array = ["a","b","c","d","e","f"];
console.log(array.slice(-1))     //["f"]
console.log(array.slice(-2))     //["e","f"]
console.log(array.slice(1))      //["b", "c", "d", "e", "f"]
arrays.slice(1,4)                // ["b", "c", "d"]

 

2. Splicing:

concat : concatenate an array with another array and return the concatenated array 

var array = ["a","b","c"];
var array1 = ["a","b","c"];
var array2 = array.concat(array1);
console.log(array2)    // ["a", "b", "c", "a", "b", "c"]

 

join : concatenate each item in the array into a string according to the specified delimiter

var array = ["a","b","c","d","e","f"];
var array1 = array.join("");   //"abcdef"
var array2 = array.join("_");  //"a_b_c_d_e_f"

 

3. Sort:

reverse : reversed array return value reversed array original array change

var   arr = [1, 2, 3, 4, 5 ];
arr.reverse()     // [5, 4, 3, 2, 1]

 

sort : Bubble sort ba reverse ab ascending order based on anonymous functions, but it should be noted that this method is sorted by Ascii code (not very practical)

var arr = [1,3,7,5,14,24 ];
arr.sort();
console.log(arr);  ==>[1,14,24,3,5,7]

 

4. Common methods:

indexOf : returns the index of the retrieved item in the array (the index of the first occurrence)

var arr = ['apple','orange','pear'];
 
console.log( "found:", arr.indexOf("orange")); // return index 1

 

lastIndexOf : Returns the last index of the retrieved item in the array

var arr = ['apple','orange','orange','pear'];
 
console.log("found:", arr.lastIndexOf("orange"));// 返回索引2

 

forEach : loop through the array parameter is an anonymous function that returns undefined by default

var array1 = [1,2,3,4,5,6];
var x = array1.forEach(function(value,index,array){
     array[index] = value+1;
     return array;
});
console.log( "new array"+x); // no matter what the above returns, x is undefined 
console.log("original array"+array1); // [2,3,4,5,6,7]

 

map : looping through the array parameter is an anonymous function

var array1 = [1,2,3,4,5,6];
var x = array1.map(function(value,index,array){
    return value+1;
});
console.log( "new array"+x);          // [2,3,4,5,6,7]; 
console.log("original array"+array1);     // [1,2,3,4 ,5,6];

 

filter : Creates a new array of matching filter conditions

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); // [
                          {"name":"orange", "count": 5},
                          {"name":"orange", "count": 16}
                          ]

 

reduce : Each value in the array (from left to right) starts to be merged and ends up with a single value.

var arr = [1,2,3,4];
var newarr = arr.reduce(function(x, y) {
        return x * 10 + y;
    });
console.log(newarr)   // 1234

/**
* reduce(callback, initialValue) will pass in two variables
* Callback function (callback), initial value (initialValue)
* Generally speaking, prev starts from 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.
*/

var arr = ["apple","orange"];
function noPassValue(){
  return arr.reduce(function(prev,next){
    console.log("prev:",prev);    //prev: apple
    console.log("next:",next);    //prev: orange
     
    return prev + " " +next;    //"apple orange"
  });
}
noPassValue();


var arr = ["apple","orange"];
function passValue(){
  return arr.reduce(function(prev,next){
    console.log("prev:",prev);    //  {}       {"apple"}
    console.log("next:",next);    //"apple"    "orange"
     
    prev[next] = 1;               //在此赋值{}["apple"]=1  -->{apple: 1}
    return prev;                  //{apple: 1, orange: 1}
  },{});
}
passValue ();

// From this, it can be achieved: count how many unique 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());   //{apple: 2, orange: 3, pear: 1}
A student's final grade is as follows

var result = [{
        subject: 'math',
        score: 88
    },
    {
        subject: 'chinese',
        score: 95
    },
    {
        subject: 'english',
        score: 80
    }];
How can I find the student's total score?
Obviously, using for loops can be very simple to draw conclusions
var sum = 0;
for(var i=0; i<result.length; i++) {
    sum += result[i].score;
}
But our purpose is to abandon the for loop, so use reduce to solve this problem, the following is equivalent to setting the initial score to 0,
var sum = result.reduce(function(prev, cur) {
    return cur.score + prev;
}, 0);

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324920260&siteId=291194637