天天看点

JavaScript Array 总结

构造函数

  1. 直接使用中括号创建,如:

    let arr = [1, 2]

  2. 使用

    new

    创建空数组(不加

    new

    效果也一样),如:

    let arr = new Array(5)

    。其中 5 为数组长度(与其它编程语言不同,此时 Array 的长度即为5,而不是0),数组创建时其中元素均为

    empty

    empty

    undefined

    在操作数组时的主要区别在于:使用数组的

    forEach()

    方法遍历时会自动忽略空位, 而使用

    for

    循环则会将

    empty

    转换为

    undefined

    并遍历,且使用数组的

    map

    方法时会跳过

    empty

    的代码执行,但会返回

    empty

  3. 使用

    new

    创建有初值的数组,如:

    let arr = new Array(1, 2, 3)

实例属性

  1. length

    length 属性为 Array 对象的长度,可以直接进行设置,若将 length 变大,则使用 undefined 填充,变小则将丢弃后面的数据

静态方法

  1. Array.from()

    从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例

    console.log(Array.from('foo'));
    // expected output: Array ["f", "o", "o"]
    
    console.log(Array.from([1, 2, 3], x => x + x));
    // expected output: Array [2, 4, 6]
               
  2. Array.isArray()

    用于确定传递的值是否是一个 Array

  3. Array.of()

    创建一个具有可变数量参数的新数组实例,而不考虑参数的数量或类型。与构造函数类似,不同点在于只有一个整数参数的时候不是创建指定长度的数组

实例方法

  1. 遍历
    • Array.prototype.forEach()

      对数组的每个元素执行一次给定的函数,无返回值

      const array1 = ['a', 'b', 'c'];
      array1.forEach(element => console.log(element));
                 
    • Array.prototype.reduce()

      对数组中的每个元素执行一个由您提供的 reducer 函数(升序执行),将其结果汇总为单个返回值

      const array1 = [1, 2, 3, 4];
      const reducer = (accumulator, currentValue) => accumulator + currentValue;
      
      // 1 + 2 + 3 + 4
      console.log(array1.reduce(reducer));
      // expected output: 10
      
      // 5 + 1 + 2 + 3 + 4
      console.log(array1.reduce(reducer, 5));
      // expected output: 15
                 
    • Array.prototype.reduceRight()

      同上 Array.prototype.reduce() ,只是方向相反

    • Array.prototype.some()

      测试数组中是不是至少有1个元素通过了被提供的函数测试

      **注意:**如果用一个空数组进行测试,在任何情况下它返回的都是

      false

      const array = [1, 2, 3, 4, 5];
      
      // checks whether an element is even
      const even = (element) => element % 2 === 0;
      
      console.log(array.some(even));
      // expected output: true
                 
    • Array.prototype.every()

      测试一个数组内的所有元素是否都能通过某个指定函数的测试

      const isBelowThreshold = (currentValue) => currentValue < 40;
      
      const array1 = [1, 30, 39, 29, 10, 13];
      
      console.log(array1.every(isBelowThreshold));
      // expected output: true
                 
  2. 衍生
    • Array.prototype.concat()

      用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组

      const array1 = ['a', 'b', 'c'];
      const array2 = ['d', 'e', 'f'];
      const array3 = array1.concat(array2);
      
      console.log(array3);
      // expected output: Array ["a", "b", "c", "d", "e", "f"]
                 
    • Array.prototype.slice()

      返回一个新的数组对象,这一对象是一个由

      begin

      end

      决定的原数组的浅拷贝(包括

      begin

      ,不包括

      end

      )。原始数组不会被改变
      const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
      
      console.log(animals.slice(2));
      // expected output: Array ["camel", "duck", "elephant"]
      
      console.log(animals.slice(2, 4));
      // expected output: Array ["camel", "duck"]
      
      console.log(animals.slice(1, 5));
      // expected output: Array ["bison", "camel", "duck", "elephant"]
                 
    • Array.prototype.flat()

      按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回

      const arr1 = [0, 1, 2, [3, 4]];
      
      console.log(arr1.flat());
      // expected output: [0, 1, 2, 3, 4]
      
      const arr2 = [0, 1, 2, [[[3, 4]]]];
      
      console.log(arr2.flat(2));
      // expected output: [0, 1, 2, [3, 4]]
                 
    • Array.prototype.map()

      创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值

      const array1 = [1, 4, 9, 16];
      
      // pass a function to map
      const map1 = array1.map(x => x * 2);
      
      console.log(map1);
      // expected output: Array [2, 8, 18, 32]
                 
    • Array.prototype.flatMap()

      首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。它与 map 连着深度值为1的 flat 几乎相同,但 flatMap 通常在合并成一种方法的效率稍微高一些

      var arr1 = [1, 2, 3, 4];
      
      arr1.flatMap(x => [x * 2]);
      // [2, 4, 6, 8]
      
      // only one level is flattened
      arr1.flatMap(x => [[x * 2]]);
      // [[2], [4], [6], [8]]
                 
    • Array.prototype.filter()

      创建一个新数组, 其包含通过所提供函数实现的测试的所有元素

      const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
      
      const result = words.filter(word => word.length > 6);
      
      console.log(result);
      // expected output: Array ["exuberant", "destruction", "present"]
                 
  3. 查找
    • Array.prototype.find()

      返回数组中满足提供的测试函数的第一个元素的值。否则返回

      undefined

      const array1 = [5, 12, 8, 130, 44];
      
      const found = array1.find(element => element > 10);
      
      console.log(found);
      // expected output: 12
                 
    • Array.prototype.findIndex()

      返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1

      const array1 = [5, 12, 8, 130, 44];
      
      const isLargeNumber = (element) => element > 13;
      
      console.log(array1.findIndex(isLargeNumber));
      // expected output: 3
                 
    • Array.prototype.includes()

      判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false

      const array1 = [1, 2, 3];
      
      console.log(array1.includes(2));
      // expected output: true
      
      const pets = ['cat', 'dog', 'bat'];
      
      console.log(pets.includes('cat'));
      // expected output: true
      
      console.log(pets.includes('at'));
      // expected output: false
                 
    • Array.prototype.indexOf()

      返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1

      const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
      
      console.log(beasts.indexOf('bison'));
      // expected output: 1
      
      // start from index 2
      console.log(beasts.indexOf('bison', 2));
      // expected output: 4
      
      console.log(beasts.indexOf('giraffe'));
      // expected output: -1
                 
    • Array.prototype.lastIndexOf()

      返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。从数组的后面向前查找,从

      fromIndex

      处开始
      const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];
      
      console.log(animals.lastIndexOf('Dodo'));
      // expected output: 3
      
      console.log(animals.lastIndexOf('Tiger'));
      // expected output: 1
                 
  4. 修改
    • Array.prototype.fill()

      用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引

      const array1 = [1, 2, 3, 4];
      
      // fill with 0 from position 2 until position 4
      console.log(array1.fill(0, 2, 4));
      // expected output: [1, 2, 0, 0]
      
      // fill with 5 from position 1
      console.log(array1.fill(5, 1));
      // expected output: [1, 5, 5, 5]
      
      console.log(array1.fill(6));
      // expected output: [6, 6, 6, 6]
                 
    • Array.prototype.pop()

      从数组中删除最后一个元素,并返回该元素的值。此方法更改数组的长度

    • Array.prototype.push()

      将一个或多个元素添加到数组的末尾,并返回该数组的新长度

    • Array.prototype.unshift()

      将一个或多个元素添加到数组的开头,并返回该数组的新长度。

    • Array.prototype.shift()

      从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度

    • Array.prototype.splice()

      通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。第一个参数为索引,第二个参数为从指定索引开始删除后面的元素的个数,其它参数为插入索引位置的元素

      const months = ['Jan', 'March', 'April', 'June'];
      months.splice(1, 0, 'Feb');
      // inserts at index 1
      console.log(months);
      // expected output: Array ["Jan", "Feb", "March", "April", "June"]
      
      months.splice(4, 1, 'May');
      // replaces 1 element at index 4
      console.log(months);
      // expected output: Array ["Jan", "Feb", "March", "April", "May"]
                 
    • Array.prototype.reverse()

      将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。该方法会改变原数组

    • Array.prototype.sort()

      用原地算法对数组的元素进行排序,并返回数组。默认排序顺序是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的

      由于它取决于具体实现,因此无法保证排序的时间和空间复杂性

      const arr = [1, 30, 4, 21, 100000];
      arr.sort();
      console.log(arr);
      // expected output: Array [1, 100000, 21, 30, 4]
      
      arr.sort(function(a,b){
          return a-b;
      });
      console.log(arr);
      // expected output: Array [1, 4, 21, 30, 100000]
                 
    • Array.prototype.copyWithin()

      浅复制数组的一部分到同一数组中的另一个位置,并返回它,不会改变原数组的长度

      const array1 = ['a', 'b', 'c', 'd', 'e'];
      
      // copy to index 0 the element at index 3
      console.log(array1.copyWithin(0, 3, 4));
      // expected output: Array ["d", "b", "c", "d", "e"]
      
      // copy to index 1 all elements from index 3 to the end
      console.log(array1.copyWithin(1, 3));
      // expected output: Array ["d", "d", "e", "d", "e"]
                 
  5. 转字符串
    • Array.prototype.join()

      将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串

      const elements = ['Fire', 'Air', 'Water'];
      
      console.log(elements.join());
      // expected output: "Fire,Air,Water"
      
      console.log(elements.join(''));
      // expected output: "FireAirWater"
      
      console.log(elements.join('-'));
      // expected output: "Fire-Air-Water"