• ES5和ES6数组方法


    ES5 方法

    indexOf和lastIndexOf

    都接受两个参数:查找的值、查找起始位置不存在,返回 -1 ;存在,返回位置。indexOf 是从前往后查找, lastIndexOf 是从后往前查找。

    var a = [2, 9, 9];
    a.indexOf(2); // 0
    a.indexOf(7); // -1
    
    if (a.indexOf(7) === -1) {
      // element doesn't exist in array
    }
    
    var numbers = [2, 5, 9, 2];
    numbers.lastIndexOf(2);     // 3
    numbers.lastIndexOf(7);     // -1
    numbers.lastIndexOf(2, 3);  // 3
    numbers.lastIndexOf(2, 2);  // 0
    numbers.lastIndexOf(2, -2); // 0
    numbers.lastIndexOf(2, -1); // 3
    

    push和pop

    push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度。末尾添加,返回的是长度,会改变原数组

    var a = [2,3,4];
    var b = a.push(5);
    console.log(a);  //[2,3,4,5]
    console.log(b);  //4
    //push方法可以一次添加多个元素push(data1,data2....)
    

    pop() 方法用于删除并返回数组的最后一个元素。返回最后一个元素,会改变原数组

    var arr = [2,3,4];
    console.log(arr.pop()); //4
    console.log(arr);  //[2,3]
    

    shift和unshift

    shift() 方法用于把数组的第一个元素从其中删除和pop()是相反的,并返回第一个元素的值。返回第一个元素,改变原数组。

    var arr = [2,3,4];
    console.log(arr.shift()); //2
    console.log(arr);  //[3,4]
    

    unshift() 方法可向数组的开头添加一个或更多元素,并返回新的长度。返回新长度,改变原数组

    var arr = [2,3,4,5];
    console.log(arr.unshift(3,6)); //6
    console.log(arr); //[3, 6, 2, 3, 4, 5]
    

    注意:该方法可以不传参数,不传参数就是不增加元素

    slice

    slice译为“切片”,发音:slīs,和stringsubstring()相似,截取一部分元素。返回一个新的数组,包含从 start 到 end (不包括该元素)的 arrayObject 中的元素。返回选定的元素,该方法不会修改原数组

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

    splice

    这个方法有三种用法:

    删除

    语法:array.splice(index,n)
    index:数组中需要删除数据的起始位置;
    n:需要删除的元素,数据的个数;

    插入

    语法:array.splice(index,0,data1,data2,....)
    index:数组中需要插入数据的起始位置;
    0:删除的个数为0;
    data1,data2:需要插入的元素,用逗号隔开;

    替换

    语法:array.splice(index,n,data1,data2,......);
    index:需要替换的元素的起始位置;
    n:需要替换的元素的个数,实质是删除;
    data1,data2:需要插入元素,用逗号隔开;

    splice() 方法可删除从 index 处开始的零个或多个元素,并且用参数列表中声明的一个或多个值来替换那些被删除的元素。如果从 arrayObject 中删除了元素,则返回的是含有被删除的元素的数组。splice() 方法会直接对数组进行修改。

    var a = [5,6,7,8];
    console.log(a.splice(1,0,9)); //[] 插入,数组从下标为1的开始加入元素9
    console.log(a);  // [5, 9, 6, 7, 8]
    
    var b = [5,6,7,8];
    console.log(b.splice(1,2,3));  //[6, 7] 删除,从第二个数开始删除两个元素,加一个3
    console.log(b); //[5, 3, 8]
    

    concat

    concat() 方法用于连接两个或多个数组。该方法不会改变现有的数组,仅会返回被连接数组的一个副本

    var arr1 = [1,2,3];
    var arr2 = [4,5];
    var arr3 = arr1.concat(arr2);
    console.log(arr1); //[1, 2, 3]
    console.log(arr3); //[1, 2, 3, 4, 5]
    

    join

    join() 方法用于把数组中的所有元素放入一个字符串。元素是通过指定的分隔符进行分隔的,默认使用','号分割,不改变原数组。

    var arr = [2,3,4];
    console.log(arr.join());  //2,3,4
    console.log(arr);  //[2, 3, 4]
    

    sort

    按照 Unicode code 位置排序,默认升序

    var fruit = ['cherries', 'apples', 'bananas'];
    fruit.sort(); // ['apples', 'bananas', 'cherries']
    
    var scores = [1, 10, 21, 2];
    scores.sort(); // [1, 10, 2, 21]
    

    reverse

    reverse() 方法用于颠倒数组中元素的顺序。返回的是颠倒后的数组,会改变原数组。

    var arr = [2,3,4];
    console.log(arr.reverse()); //[4, 3, 2]
    console.log(arr);  //[4, 3, 2]
    

    every和some

    every对数组的每一项都运行给定的函数,每一项都返回 ture,则返回 true

    function isBigEnough(element, index, array) {
      return element < 10;
    }    
    
    [2, 5, 8, 3, 4].every(isBigEnough);   // true
    

    some对数组的每一项都运行给定的函数,任意一项都返回 ture,则返回 true

    function compare(element, index, array) {
      return element > 10;
    }    
    
    [2, 5, 8, 1, 4].some(compare);  // false
    [12, 5, 8, 1, 4].some(compare); // true
    

    filter

    对数组的每一项都运行给定的函数,返回 结果为 ture 的项组成的数组

    var words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"];
    
    var longWords = words.filter(function(word){
      return word.length > 6;
    });
    //["exuberant", "destruction", "present"]
    

    map

    对数组的每一项都运行给定的函数,返回每次函数调用的结果组成一个新数组

    var numbers = [1, 5, 10, 15];
    var doubles = numbers.map(function(x) {
       return x * 2;
    });
    // doubles is now [2, 10, 20, 30]
    // numbers is still [1, 5, 10, 15]
    

    forEach

    数组遍历

    const items = ['item1', 'item2', 'item3'];
    const copy = [];    
    items.forEach(function(item){
      copy.push(item)
    });
    

    reduce

    reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。第二个参数是初始值。

    reduce中回调函数的参数,这个回调函数中有4个参数,意思分别为:

    • prev: 第一项的值或者上一次叠加的结果值
    • cur: 当前会参与叠加的项
    • index: 当前值的索引
    • arr: 数组本身

    数组求和

    var total = [ 0, 1, 2, 3 ].reduce((acc, cur ) => {
        return acc + cur
    }, 0);
    console.log(total)   // 6
    

    计算数组中每个元素出现的次数实现一:

    let names = ['tom', 'jim', 'jack', 'tom', 'jack'];
    
    const countNames = names.reduce((allNames, name) => {
      if (name in allNames) {
        allNames[name] ++;
      }
      else {
        allNames[name] = 1;
      }
      return allNames;
    }, {});
    
    console.log(countNames)  // { tom: 2, jim: 1, jack: 2 }
    

    计算数组中某个元素出现的次数实现二:

    const arraySum = (arr, val) => arr.reduce((acc, cur) => {
        return cur == val ? acc + 1 : acc + 0
    }, 0);
    
    let arr = [ 0, 1, 3, 0, 2, 0, 2, 3 ]
    console.log(arraySum(arr, 0)) // 数组arr中 0 元素出现的次数为3
    

    数组去重实现一

    let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
    let result = arr.sort().reduce((init, current) => {
        if (init.length === 0 || init[init.length - 1] !== current) {
            init.push(current);
        }
        return init;
    }, []);
    console.log(result); //[1,2,3,4,5]
    

    数组去重实现二

    const dedupe = (array) => {
        return Array.from(new Set(array));
    }
    console.log(dedupe([1, 1, 2, 3])) //[1,2,3]
    

    ES6 方法

    静态函数Array.from(..)

    将类似数组的对象(array-like object)和可遍历(iterable)的对象转为真正的数组,比如:
    1.部署了Iterator接口的对象,比如:Set,Map,Array。
    2.类数组对象,什么叫类数组对象,就是一个对象必须有length属性,没有length,转出来的就是空数组。

    转换map

    将Map对象的键值对转换成一个二维数组。

    const map1 = new Map();
    map1.set('k1', 1);
    map1.set('k2', 2);
    map1.set('k3', 3);
    console.log('%s', JSON.stringify(Array.from(map1)))//[["k1",1],["k2",2],["k3",3]]
    

    转换set

    将Set对象的元素转换成一个数组。

    const set1 = new Set();
    set1.add(1).add(2).add(3)
    console.log('%s', JSON.stringify(Array.from(set1)) //[1,2,3]
    

    转换字符串

    可以吧ascii的字符串拆解成一个数据,也可以准确的将unicode字符串拆解成数组。

    console.log('%s', JSON.stringify(Array.from('hello world')))//["h","e","l","l","o"," ","w","o","r","l","d"]
    console.log('%s', JSON.stringify(Array.from('u535au5ba2u56ed')))//["博","客","园"]
    

    类数组对象

    一个类数组对象必须要有length,他们的元素属性名必须是数值或者可以转换成数值的字符。

    console.log('%s', JSON.stringify(Array.from({
      0: '0',
      1: '1',
      3: '3',
      length:4
    }))) //["0","1",null,"3"]
    

    静态函数Array.of(..)

    ES6为Array增加了of函数用已一种明确的含义将一个或多个值转换成数组。

    因为,用new Array()构造数组的时候,是有二意性的。
    构造时,传一个参数,表示生成多大的数组。
    构造时,传多个参数,每个参数都是数组的一个元素。

    const arr1 = new Array()
    const arr2 = new Array(5)
    const arr3 = new Array(1, 3, '白色', {p1: 'v1'})
    console.log('%s', JSON.stringify(arr1)) //[]
    console.log('%s', JSON.stringify(arr2)) //[null,null,null,null,null]
    console.log('%s', JSON.stringify(arr3)) //[1,3,"白色",{"p1":"v1"}]
    

    ES6增加的Array.of()方法,只有一个含义,of的参数就是表示转换后数组的元素。

    const arr4 = Array.of()
    const arr5 = Array.of(5)
    const arr6 = Array.of(1, 3, '白色', {p1: 'v1'})
    console.log('%s', JSON.stringify(arr4)) //[]
    console.log('%s', JSON.stringify(arr5)) //[5]
    console.log('%s', JSON.stringify(arr6)) //
    

    原型方法find(..)和findIndex(..)

    传入一个回调函数,找到数组中符合当前搜索规则的第一个元素,返回它,并且终止搜索。

    查找函数有三个参数:

    • value:每一次迭代查找的数组元素。
    • index:每一次迭代查找的数组元素索引。
    • arr:被查找的数组。
    const arr = [1, "2", 3, 3, "2"]
    console.log(arr.find(n => typeof n === "number")) // 1
    
    const arr = [1, "2", 3, 3, "2"]
    console.log(arr.findIndex(n => typeof n === "number")) // 0
    
    const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    var ret1 = arr1.find((value, index, arr) => {
      return value > 4
    })
    
    var ret2 = arr1.find((value, index, arr) => {
      return value > 14
    })
    console.log('%s', ret1)
    console.log('%s', ret2)
    

    原型方法fill(..)

    用新元素替换掉数组内的元素,可以指定替换下标范围。

    Array.prototype.fill(value, start, end)
    
    • value:(必填),填充值。
    • start:填充起始位置,可以省略。
    • end:填充结束位置,可以省略,实际结束位置是end-1。

    采用一默认值填初始化数组

    const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    arr1.fill(7)
    console.log('%s', arr1)//7,7,7,7,7,7,7,7,7,7,7
    

    开始和结束位置填充

    const arr3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    arr3.fill(7, 2, 5)
    console.log('%s', arr3)//1,2,7,7,7,6,7,8,9,10,11
    

    原型方法copyWithin(..)

    在当前数组内部,将指定位置的成员复制到其他位置

    Array.prototype.copyWithin(target, start = 0, end = this.length)
    
    • target:(必填),目的起始位置。
    • start:(可选),复制源的起始位置,可以是负数。
    • end:(可选),复制源的结束位置,可以是负数,实际结束位置是end-1。

    默认值复制

    const arr = [1, 2, 3, 4, 5]
    arr.copyWithin(3) 
    //相当于arr.copyWithin(3,0,arr.length)
    console.log('%s', JSON.stringify(arr))//[1, 2, 3, 1, 2]
    

    从下标为3的元素开始,复制数组,所以4, 5被替换成1, 2

    结束位置省略

    const arr = [1, 2, 3, 4, 5]
    arr.copyWithin(3, 1)
    console.log('%s', JSON.stringify(arr))// [1,2,3,2,3]
    

    从下标为3的元素开始,复制数组,指定复制的第一个元素下标为1,所以4, 5被替换成2, 3

    开始和结束位置

    const arr = [1, 2, 3, 4, 5]
    arr.copyWithin(3, 1, 2)
    console.log('%s', JSON.stringify(arr))// [1,2,3,2,5]
    

    从下标为3的元素开始,复制数组,指定复制的第一个元素下标为1,结束位置为2,所以4被替换成2

    负数位置
    start和end都可以是负数,负数表示从右边数过来第几个。

    const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    arr.copyWithin(3, -3, -2)
    console.log('%s', JSON.stringify(arr))
    

    原型方法entries()、values()、keys

    ES6提供了entries(),keys(),values()方法返回数组的遍历器,对于遍历器(Iterator)可以使用for...of进行便利,也可是使用entries()返回的遍历器Iterator.next()方法进行遍历。

    entries(..)

    //数组
    const arr = ['a', 'b', 'c'];
    for(let v of arr.entries()) {
      console.log(v)
    }
    // [0, 'a'] [1, 'b'] [2, 'c']
    
    //Set
    const arr = new Set(['a', 'b', 'c']);
    for(let v of arr.entries()) {
      console.log(v)
    }
    // ['a', 'a'] ['b', 'b'] ['c', 'c']
    
    //Map
    const arr = new Map();
    arr.set('a', 'a');
    arr.set('b', 'b');
    for(let v of arr.entries()) {
      console.log(v)
    }
    // ['a', 'a'] ['b', 'b']
    

    values()返回的是数组元素值的遍历器。

    //数组
    const arr = ['a', 'b', 'c'];
    for(let v of arr.values()) {
      console.log(v)
    }
    //'a' 'b' 'c'
    
    //Set
    const arr = new Set(['a', 'b', 'c']);
    for(let v of arr.values()) {
      console.log(v)
    }
    // 'a' 'b' 'c'
    
    //Map
    const arr = new Map();
    arr.set('a', 'a');
    arr.set('b', 'b');
    for(let v of arr.values()) {
      console.log(v)
    }
    // 'a' 'b'
    

    keys()返回的是数组元素索引号的遍历器。

    //数组
    const arr = ['a', 'b', 'c'];
    for(let v of arr.keys()) {
      console.log(v)
    }
    // 0 1 2
    
    //Set
    const arr = new Set(['a', 'b', 'c']);
    for(let v of arr.keys()) {
      console.log(v)
    }
    // 'a' 'b' 'c'
    
    //Map
    const arr = new Map();
    arr.set('a', 'a');
    arr.set('b', 'b');
    for(let v of arr.keys()) {
      console.log(v)
    }
    // 'a' 'b'
    

    原型方法includes(..)

    在ES5,Array已经提供了indexOf用来查找某个元素的位置,如果不存在就返回-1,但是这个函数在判断数组是否包含某个元素时有两个小不足:

    • 第一个是它会返回-1和元素的位置来表示是否包含,在定位方面是没问题,就是不够语义化
    • 另一个问题是不能判断是否有NaN的元素。
    const arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', NaN]
    console.log('%s', arr1.indexOf(NaN))//-1
    
    const arr2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', NaN]
    console.log('%s', arr2.includes('c')) //true
    console.log('%s', arr2.includes('z')) //false
    console.log('%s', arr2.includes(NaN)) //true
    

    参考

  • 相关阅读:
    1012 The Best Rank (25 分)(排序)
    1011. World Cup Betting (20)(查找元素)
    1009 Product of Polynomials (25 分)(模拟)
    1008 Elevator (20 分)(数学问题)
    1006 Sign In and Sign Out (25 分)(查找元素)
    1005 Spell It Right (20 分)(字符串处理)
    Kafka Connect 出现ERROR Failed to flush WorkerSourceTask{id=local-file-source-0}, timed out while wait
    flume、kafka、avro组成的消息系统
    Java23种设计模式总结【转载】
    Java编程 思维导图
  • 原文地址:https://www.cnblogs.com/ricolee/p/js-array-method.html
Copyright © 2020-2023  润新知