zoukankan      html  css  js  c++  java
  • 数组方法总结

    1.去重 

      new Set()

    new Set([1,2,3,4,2]) //[1,2,3,4]
    

    2.替换

    splice(1,1,'5')
    

    3.遍历

    array1.map((item,index,array)=>{return item*2})
     var friends = [
        { name: ‘John’, age: 22 },
        { name: ‘Peter’, age: 23 },
        { name: ‘Mark’, age: 24 },
        { name: ‘Maria’, age: 22 },
        { name: ‘Monica’, age: 21 },
        { name: ‘Martha’, age: 19 },
    ]
    Array.from(friends, ({name}) => name);
    

    4.清空

    length = 0
    

    5.数组转对象 

     var fruits = [“banana”, “apple”, “orange”, “watermelon”];
      var fruitsObj = { …fruits };
    

      

    6.填充数组

    new Array(10).fill(“1”)
    

    7.合并数组

    food = […fruits, …meat, …vegetables];
    array1.concat(array2,...,arrayn)

    8.两个数组的交集

     […new Set(numOne)].filter(item => numTwo.includes(item));
    

    9.去除假值

    在JS中,假值有:false、0、''、null、NaN、undefined

    var mixedArr = [0, 'blue', '', NaN, 9, true, undefined, 'white', false];
    var trueArr = mixedArr.filter(Boolean);
    

    10.倒序 reverse()

    11.排序

    function sortFN(pro1,pro2){
        return function(a,b){
              return a.pro1 - b.pro2
        }
    }
    
    function sortFN(pro1,pro2){
        return function(a,b){
             if(a.pro1 == b.pro1){return a.pro2 - b.pro2}
              return a.pro1 - b.pro1
        }
    }    
    

    12.求和

    nums.reduce((x, y) => x + y);

    13.其他补充:

    push()     返回修改后的长度。

    pop()       返回移除的那个值,减少数组的length

    shift()       删除原数组第一项,并返回删除元素的值;如果数组为空则返回undefined 。

    unshift()   将参数添加到原数组开头,并返回数组的长度

    join()

    indexof() lastIndexOf()   接收两个参数:要查找的项和(可选的)表示查找起点位置的索引

    forEach()  

    arr.forEach(function(x, index, a){
    console.log(x + '|' + index + '|' + (a === arr));
    }); 

    filter(fn)

    some(fn)

    every (fn)  every(fn) fn :条件() 

    arry1.includes(item) => true /false

    var arr3 = arr.some(function(x) {
        return x < 1;
    });  
  • 相关阅读:
    [leetcode]Remove Nth Node From End of List @ Python
    [leetcode]Swap Nodes in Pairs @ Python
    [leetcode]Linked List Cycle II @ Python
    [leetcode]Linked List Cycle @ Python
    [leetcode]LRU Cache @ Python
    [leetcode]Reorder List @ Python
    [leetcode]Insertion Sort List @ Python
    [leetcode]Sort List @ Python
    [leetcode]3Sum Closest @ Python
    [elk]elasticsearch实现冷热数据分离
  • 原文地址:https://www.cnblogs.com/zhouhongdan/p/12613095.html
Copyright © 2011-2022 走看看