JavaScript数组常用方法总结

参考:https://www.infoq.cn/article/3L*kK19KH2Ey7GIVBGsN

map、filter、reduce

  • map:返回一个数组,其中每个元素都使用指定函数进行过转换。
    const arr = [1, 2, 3, 4, 5, 6];
    const mapped = arr.map(el => el + 20);
    console.log(mapped);
    // [21, 22, 23, 24, 25, 26]
  • filter:返回一个数组,只有当指定函数返回 true 时,相应的元素才会被包含在这个数组中。
    const arr = [1, 2, 3, 4, 5, 6];
    const filtered = arr.filter(el => el === 2 || el === 4);
    console.log(filtered);
    // [2, 4]
  • reduce:基于给定函数累加值。
    const arr = [1, 2, 3, 4, 5, 6];
    const reduced = arr.reduce((total, current) => total + current);
    console.log(reduced);
    // 21

find、findIndex、indexOf

  • find:返回与指定条件匹配的第一个实例,不会继续查找其他匹配的实例。
    const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    const found = arr.find(el => el > 5);
    console.log(found);
    // 6
  • 这与 find 几乎完全相同,但不返回第一个匹配的元素,而是返回第一个匹配元素的索引。
    const arr = ['Nick', 'Frank', 'Joe', 'Frank'];
    const foundIndex = arr.findIndex(el => el === 'Frank');
    console.log(foundIndex);
    // 1
  • 与 findIndex 几乎完全相同,但它的参数不是一个函数,而是一个简单的值。
    const arr = ['Nick', 'Frank', 'Joe', 'Frank'];
    const foundIndex = arr.indexOf('Frank');
    console.log(foundIndex);
    // 1

push、pop、shift、unshift

  • push:这是一个相对简单的方法,它将一个项添加到数组的末尾。它就地修改数组,函数本身会返回添加到数组中的项。
    let arr = [1, 2, 3, 4];
    const popped = arr.pop();
    console.log(arr);
    // [1, 2, 3]
    console.log(popped);
    // 4
  • pop:从数组中删除最后一项。同样,它也是就地修改数组。函数本身返回从数组中删除的项。
    let arr = [1, 2, 3, 4];
    const popped = arr.pop();
    console.log(arr);
    // [1, 2, 3]
    console.log(popped);
    // 4
  • shift:从数组中删除第一个项。同样,它也是就地修改数组。函数本身返回从数组中删除的项。
    let arr = [1, 2, 3, 4];
    const shifted = arr.shift();
    console.log(arr);
    // [2, 3, 4]
    console.log(shifted);
    // 1
  • unshift:将一个或多个元素添加到数组的开头。同样,它也是就地修改数组。与其他方法不同的是,函数本身返回数组最新的长度。
    let arr = [1, 2, 3, 4];
    const unshifted = arr.unshift(5, 6, 7);
    console.log(arr);
    // [5, 6, 7, 1, 2, 3, 4]
    console.log(unshifted);
    // 7

splice、slice

  • splice:通过删除或替换现有元素或者添加新元素来修改数组的内容。这个方法也是就地修改数组。
    let arr = ['a', 'c', 'd', 'e'];
    arr.splice(1, 0, 'b');
    console.log(arr); 
    // ['a', 'b', 'c', 'd', 'e']
  • slice:从指定的起始位置和结束位置之前返回数组的浅拷贝。如果未指定结束位置,则返回数组的其余部分。
    let arr = ['a', 'b', 'c', 'd', 'e'];
    const sliced = arr.slice(2, 4);
    console.log(sliced);
    // ['c', 'd']
    console.log(arr);
    // ['a', 'b', 'c', 'd', 'e']

sort

  • sort:根据提供的函数对数组进行排序。这个方法就地修改数组。如果函数返回负数或 0,则顺序保持不变。如果返回正数,则交换元素顺序。
    let arr = [1, 7, 3, -1, 5, 7, 2];
    const sorter = (firstEl, secondEl) => firstEl - secondEl;
    arr.sort(sorter);
    console.log(arr);
    // [-1, 1, 2, 3, 5, 7, 7]
posted @ 2019-03-19 15:44  大豆F4  阅读(190)  评论(0编辑  收藏  举报