JS 操作数组方法

170 阅读3分钟

基本功能详解

1. 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"]

2. copyWithin() [es6 新增]

  • 用于从数组的指定位置拷贝元素到数组的另一个指定位置中
  • 该方法会改变现有数组,但不会改变原数组的长度
  • 语法: arr.copyWithin(target[, start[, end]])
    - target: 0 为基底的索引,复制序列到该位置。如果是负数,target 将从末尾开始计算。
    - start: 0 为基底的索引,开始复制元素的起始位置。如果是负数,start 将从末尾开始计算。
    - end: 0 为基底的索引,开始复制元素的结束位置。copyWithin 将会拷贝到该位置,但不包括 end 这个位置的元素。如果是负数, end 将从末尾开始计算。
    const array1 = ['a', 'b', 'c', 'd', 'e'];
    
    console.log(array1.copyWithin(0, 3, 4));
    // expected output: Array ["d", "b", "c", "d", "e"]

    console.log(array1.copyWithin(1, 3));
    // expected output: Array ["d", "d", "e", "d", "e"]

3. indexOf()

  • 从数组的开头(位置 0)开始向后查找。
  • 接收两个参数:要查找的项和(可选的)表示查找起点位置的索引。
  • 如果不存在,则返回-1。
   const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

   console.log(beasts.indexOf('bison'));
   // expected output: 1

   console.log(beasts.indexOf('bison', 2));
   // expected output: 4

   console.log(beasts.indexOf('giraffe'));
   // expected output: -1

4. lastIndexOf()

  • 从数组的后面向前查找,从 fromIndex 处开始
  • 接收两个参数:要查找的项和(可选的)表示查找起点位置的索引。
  • 如果不存在,则返回-1。
  const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

  console.log(animals.lastIndexOf('Dodo'));
  // expected output: 3

  console.log(animals.lastIndexOf('Tiger'));
  // expected output: 1

5.forEach()

  • 对数组进行遍历循环,对数组中的每一项运行给定函数。这个方法没有返回值
  • 语法: arr.forEach(callback(currentValue [, index [, array]])[, thisArg])
    - callback:为数组中每个元素执行的函数,该函数接收一至三个参数:
    • currentValue : 数组中正在处理的当前元素。
    • index (可选): 数组中正在处理的当前元素的索引。
    • array (可选): forEach() 方法正在操作的数组。
      - thisArg (可选):当执行回调函数 callback 时,用作 this 的值。
    const array1 = ['a', 'b', 'c'];

    array1.forEach(element => console.log(element));
    // expected output: "a"
    // expected output: "b"
    // expected output: "c"

6. map()

  • 返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
  • 按照原始数组元素顺序依次处理元素
  • 该方法不会改变原数组
   var arr = [1, 2, 3, 4, 5];
   var arr2 = arr.map(function(item){
    return item*item;
   });
   console.log(arr2);  //[1, 4, 9, 16, 25]

7. 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"]

8. shift() 和 unshift()

  • shift() 方法用于 把数组的第一个元素从其中删除,并返回第一个元素的值。
  • unshift() 方法可 向数组的开头添加一个或更多元素,并返回新的长度。
   var arr = ["Lily","lucy","Tom"];
   var count = arr.unshift("Jack","Sean");
   console.log(count);   // 5
   console.log(arr);   //["Jack", "Sean", "Lily", "lucy", "Tom"]
   var item = arr.shift();
   console.log(item);   // Jack
   console.log(arr);   // ["Sean", "Lily", "lucy", "Tom"]