Question | Common APIs for arrays

The second parameter of every(), filter(), forEach(), map(), some() methods of Array is used to point this in the function body of the first parameter to the second parameter. If no second parameter is specified, the value of this is the global object in non-strict mode and null in strict mode.

  1. connect:arr.join("连接符")

    Concatenate the elements in the array into a string using concatenation.

    arr.join("") can connect seamlessly.

  2. Stitching:arr.concat("a","b",arr1)

    Emphasis:
    (1) The original array will not be modified, and a new array will be returned.
    (2) If a parameter passed to concat() is itself an array, the elements of the array will be connected to arr instead of the array itself.

var a = [1,2,3];
a.concat(4,5); // [1,2,3,4,5]
a.concat([4,5]); // [1,2,3,4,5]
a.concat(4, [5, [6, 7]]); // [1,2,3,4,5,[6,7]]
  1. Intercept:arr.slice(start[,end])

    Emphasis:
    (1) The original array will not be modified, and a new sub-array will be returned.

    (2) Contains the head without the tail.

    (3) Omitting the second parameter means intercepting from the start position to the end.

    (4) Negative numbers are supported, indicating the number from the bottom.

  2. delete, insert, replace:arr.splice(start, deleteCount [,value1,value2...])

    emphasize:

    (1) Modify the original array directly.

    (2) Return the subarray composed of all deleted elements.

    (3) If deleteCount is 0, it means to insert an element, and the inserted element will be arranged before the element at start.

    (4) For deletion, start from start and include the element at start.

  3. Flip the array:arr.reverse()

    Emphasis: (1) Modify the original array directly.

  4. Array sorting:arr.sort()

    Emphasis:
    (1) Modify the original array directly.

    (2) By default, the array elements are arranged according to the first ASCII code from small to large.

    (3) The following comparator functions can be set to control ascending, descending or scrambling.

    (4) arr.sort(function(a,b){return a-b;});Ascending order (only numbers or strings of numbers in the array).

    (5) arr.sort(function(a,b){return b-a;});Descending order (only numbers or strings of numbers in the array).

arr.sort(function(){
    
    
	return Math.random()>.5 ? 1 : -1;
 }); // 随机打乱数组(数组中可以是任何数据类型)
  1. Find:arr.indexOf(value[,from])或arr.lastIndexOf(value[,from])

    Emphasis:
    (1) Return the index of the value in the array, if not found, return -1.

    (2) indexOf can match objects pointing to the same address

  let obj = {
    
    age: 22};
  let arr = [{
    
    name: 'Jim'}];
  arr.push(obj);
  arr.includes(obj) // 1
  arr.includes({
    
    age: 22}) // -1
  1. Loop through an array with no return value:arr.forEach(function(value,index,arr){})

  2. Loop array, with return value:arr.map(function(value,index,arr){})

  3. Array to string: String(arr)orarr.toString()

    Concatenate the elements in the array into a string with commas, similar to arr.join(",").

  4. Start stacking:arr.unshift(value1, value2......)

    Insert an element at the very beginning of the array.

    Emphasis:
    (1) Modify the original array.

    (2) Return the length of the new array.

  5. Start popping:arr.shift()

    Pop the first element of the array.

    emphasize:

    (1) Modify the original array.

    (2) Return the popped element.

  6. The end is pushed onto the stack:arr.push(value1[,value2,arr1])

    Appends an element at the end of the array.

    emphasize:

    (1) Modify the original array.

    (2) Return the length of the new array.

    (3) The appended array will not be broken up.

  7. Pop at the end:arr.pop()

    Pops the last element of the array.

    emphasize:

    (1) Modify the original array.

    (2) Return the popped element.


  1. Array.every

    All conditions are met.

// 是否全部大于0
let a = [1,2,3,4].every(item => {
    
    
    return item > 0;
});
console.log(a); // true
  1. Array.some

    Conditions are partially met.

    Determine whether there are eligible elements in the array, and exit the loop as long as it meets the conditions.

// 是否有部分大于3
let a = [1,2,3,4].some(item => {
    
    
    return item > 3;
});
console.log(a); // true
  1. Array.filter

    Filter by condition.

    Note: The filter result is an array.

const persons = [
    {
    
    name: 'Jim', age: 22},
    {
    
    name: 'Alen', age: 17},
    {
    
    name: 'Lily', age: 20}
]
 
let a = persons.filter(person => {
    
    
    return person.age > 20;
});
console.log(a)  // [{name: 'Jim', age: 22}]
  1. Array.reduce

    summary.

    The second parameter of reduce is optional, that is, the initial value is optional. When no initial value is specified, it will use the first element of the array as the initial value. The index in the function is the index of the current value in the array. When the initial value is not passed in, the index starts from 1, and the total number of loops is 1 less than the length of the array. When the initial value is passed in, the index starts from 0, which is the first element, and the array will be traversed several times as long as it is.

    Applicable scene 1: accumulation

    let a = [1,2,3,4].reduce((total, value, index, arr) => {
          
          
        return total + value;
    }, 0);
    console.log(a) // 10
    

    There are also those who like to write:

    // 其实这里的 x 就是上面的 total,只是参数名字换了一下
    let a = [1,2,3,4].reduce(function(x, y) {
          
          
        return x + y;
    });
    

    Applicable scenario 2: array processing

    // 如:获取年龄大于18岁人的名字
    const persons = [
        {
          
          name: 'Jim', age: 22},
        {
          
          name: 'Alen', age: 17},
        {
          
          name: 'Lily', age: 20}
    ]
     
    let names = persons.reduce((names, person) => {
          
          
        if (person.age > 18) {
          
          
            names.push(person.name)
        }
        return names;
    }, []);
    console.log(names) // ['Jim', 'Lily']
    

    Applicable scenario 3: converting an array to an object

    const arr = [
        {
          
          id: '1', name: 'Jim'},
        {
          
          id: '2', name: 'Lily'},
        {
          
          id: '3', name: 'Allen'}
    ]
     
    let obj = arr.reduce((acc, current) => {
          
          
        return {
          
          ...acc, [current.id]: current};
    }, {
          
          })
     
    console.log(obj)
    // {
          
          
    //     1: {id: '1', name: 'Jim'},
    //     2: {id: '2', name: 'Lily'},
    //     3: {id: '3', name: 'Allen'}
    // }
    

    Applicable scenario 4: flattening a two-dimensional array into a one-dimensional array

    const arrLevel2 = [
        ['大', '家', '好'],
        ['我', '是', '渣', '渣', '辉']
    ];
     
    let arrLevel1 = arrLevel2.reduce((acc, current) => {
          
          
        return acc.concat(current);
    }, [])
     
    console.log('arrLevel1', arrLevel1)
    // -> ["大", "家", "好", "我", "是", "渣", "渣", "辉"]
    

    Applicable scenario 5: Perform multiple calculations in one traversal

    Sometimes we need to perform multiple calculations on an array. For example, we want to calculate the maximum and minimum value of a list of numbers, we can write:

    const readings = [0.3, 1.2, 3.4, 0.2, 3.2, 5.5, 0.4];
     
    const initMinMax = {
          
          
        minReading: Number.MAX_VALUE,
        maxReading: Number.MIN_VALUE,
    };
     
    const minMax = readings.reduce((acc, current) => {
          
          
        return {
          
          
            minReading: Math.min(acc.minReading, current),
            maxReading: Math.max(acc.maxReading, current)
        }
    }, initMinMax);
     
    console.log(minMax); // -> {minReading: 0.2, maxReading: 5.5}
    

    Applicable scenario 6: Get the maximum value in the array

    let arr = [22, 19, 50, 7, 15];
    let max = arr.reduce(function(x, y) {
          
          
      return x > y ? x : y;
    }); // 50
    
  2. Array.reduceRight

    reduceRight() works reduce() the same as , except that it processes arrays from highest to lowest (right to left) array index.

    [2, 10, 60].reduceRight(function (x, y) {
          
          
      return x/y;
    });
    // => 3: (60/10)/2
    
  3. Array.find

    Find the first array member that meets the conditions, if not found, return undefined.

    const persons = [
        {
          
          id: 1, name: 'Jim', age: 22},
        {
          
          id: 2, name: 'Alen', age: 17},
        {
          
          id: 3, name: 'Lily', age: 20}
    ]
     
    let a = persons.find(person => {
          
          
        return person.id === 2;
    });
     
    console.log(a) // {id: 2, name: 'Alen', age: 17}
    
  4. Array.findIndex

    Find the position of the first array member that meets the conditions, and return -1 if not found.

    const persons = [
        {
          
          id: 1, name: 'Jim', age: 22},
        {
          
          id: 2, name: 'Alen', age: 17},
        {
          
          id: 3, name: 'Lily', age: 20}
    ]
     
    let a = persons.findIndex(person => {
          
          
        return person.id === 2;
    });
     
    console.log(a) // 1
    
  5. Array.includes

    Indicates whether a value is in the array, includes() does not accept function parameters.

    let a = [1,2,3].includes(3);
     
    console.log(a) // true
    
  6. Array.toLocaleString()

    Convert an array to a localized string. It first calls the method on all array elements toLocaleString(), then concatenates the resulting strings using the locale-specific delimiter character.

Reprinted as:
————————————————
Copyright statement: This article is the original article of CSDN blogger "huangpb0624", following the CC 4.0 BY-SA copyright agreement, please attach the original source link for reprinting and this statement.
Original link: https://blog.csdn.net/huangpb123/article/details/76861748

Guess you like

Origin blog.csdn.net/muziqwyk/article/details/127141849