《JS数组方法速成:少写代码多摸鱼》

2,485 阅读6分钟

JavaScript 数组方法大全上线!从 mapreduce,从新手小白到写代码老鸟,这篇文章告诉你:写 JS 不再需要“祈祷代码能跑”。轻松写代码,省时又省力!

静态方法

  1. Array.from(arrayLike, mapFn, thisArg)

    可迭代类数组对象创建一个新的浅拷贝实例。

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

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

console.log(Array.isArray([1, 3, 5]));
// true

实例方法

普通函数

Array.at(index)

接收一个整数值并返回该索引对应的元素,允许正数和负数

一般的python语法接受array[-1]表示最后一个元素,但是JS语法不接受。但是array.at()接受一个负数,表示倒数第几个元素。

const arr=[1,2,3,4,5]
console.log(arr.at(-1))         //5

Array.concat(value)

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

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3);
// ["a", "b", "c", "d", "e", "f"]

Arrray.copyWithin(target, start, end)

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

target:序列开始替换的目标位置

start:要复制的元素序列的起始位置,默认0

end:要复制的元素序列的结束位置,默认0

const array1 = ['a', 'b', 'c', 'd', 'e'];
console.log(array1.copyWithin(0, 3, 4));
// ["d", "b", "c", "d", "e"]
console.log(array1.copyWithin(1, 3));
["d", "d", "e", "d", "e"]

Array.fill(value, start, end)

用一个固定值填充一个数组中从起始索引(默认为 0)到终止索引。默认所有元素。

const array1 = [1, 2, 3, 4];
console.log(array1.fill(0, 2, 4));
// [1, 2, 0, 0]
​
console.log(array1.fill(5, 1));
//  [1, 5, 5, 5]
​
console.log(array1.fill(6));
//  [6, 6, 6, 6]

Array.flat(depth)

创建一个的数组,并根据指定深度递归地将所有子数组元素拼接到新的数组中。(数组扁平化)

depth:指定要提取嵌套数组的结构深度,默认值为 1。

const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());           // [0, 1, 2, 3, 4]const arr2 = [0, 1, [2, [3, [4, 5]]]];
console.log(arr2.flat());           // [0, 1, 2, Array [3, Array [4, 5]]]
​
console.log(arr2.flat(2));          // [0, 1, 2, 3, Array [4, 5]]
​
console.log(arr2.flat(Infinity));           // [0, 1, 2, 3, 4, 5]

Array.indexOf(searchElement, fromIndex)

返回数组中第一次出现给定元素的下标,如果不存在则返回 -1。

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));//  1
​
console.log(beasts.indexOf('bison', 2));//  4
console.log(beasts.indexOf('giraffe'));// -1

Array.join(separator)

将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串,用逗号或指定的分隔符字符串分隔。

seperator:分隔元素,默认是逗号。

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

Array.pop()

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

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop());// "tomato"
console.log(plants);//  ["broccoli", "cauliflower", "cabbage", "kale"]
plants.pop();
console.log(plants);// ["broccoli", "cauliflower", "cabbage"]

Array.push(element0, element1, … )

将指定的元素添加到数组的末尾,并返回新的数组长度

const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count);// 4
console.log(animals);// ["pigs", "goats", "sheep", "cows"]

Array.reverse()

就地反转数组中的元素,并返回同一数组的引用。

const array1 = ['one', 'two', 'three'];
const reversed = array1.reverse();
console.log('reversed:', reversed);//"reversed:" ["three", "two", "one"]

Array.toReversed()

它返回一个元素顺序相反的数组。

const items = [1, 2, 3];
const reversedItems = items.toReversed();
console.log(reversedItems); // [3, 2, 1]
console.log(items); // [1, 2, 3]

Array.shift()

从数组中删除第一个元素,并返回该元素的值。

const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);//  [2, 3]
console.log(firstElement);// 1

Arrya.unshift(element1, element2, /* …, */ elementN)

将指定元素添加到数组的开头,并返回数组的新长度。

const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));// 5
console.log(array1);//[4, 5, 1, 2, 3]

Array.slice(start, end)

返回一个新的数组对象,这一对象是一个由 startend 决定的原数组的浅拷贝。

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));// ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));// ["camel", "duck"]
console.log(animals.slice(1, 5));
console.log(animals.slice(-2));//  ["duck", "elephant"]
console.log(animals.slice(2, -1));// ["camel", "duck"]

Array.with(index, value)

它会返回一个新数组,其指定索引处的值会被新值替换。

const arr = [1, 2, 3, 4, 5];
console.log(arr.with(2, 6)); // [1, 2, 6, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]

Array.splice(start, deleteCount, item1, item2, …)

就地移除或者替换已存在的元素和/或添加新的元素。

start:目标元素位置

deleteCount:删除元素数量

itemN:加入数组的元素

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
console.log(months);//  ["Jan", "Feb", "March", "April", "June"]
​
months.splice(4, 1, 'May');
console.log(months);//  ["Jan", "Feb", "March", "April", "May"]

Array.toSpliced(start, deleteCount, item1, item2, itemN)

它返回一个数组,并在给定的索引处删除和/或替换了一些元素。

const months = ["Jan", "Mar", "Apr", "May"];
const months2 = months.toSpliced(1, 0, "Feb");
console.log(months2); // ["Jan", "Feb", "Mar", "Apr", "May"]
console.log(months); // ["Jan", "Mar", "Apr", "May"]

Array.toLocaleString(locales, options)

返回一个字符串,表示数组中的所有元素。每个元素通过调用它们自己的 toLocaleString 方法转换为字符串,并且使用特定于语言环境的字符串(例如逗号“,”)分隔开。

const array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
const localeString = array1.toLocaleString('en', { timeZone: 'UTC' });
console.log(localeString);  // "1,a,12/21/1997, 2:12:00 PM",

Array.toString()

返回一个字符串,表示指定的数组及其元素。

const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString());//"1,2,a,1a"
高阶函数

Array.every(callbackFn, thisArg)

测试一个数组内的所有元素是否都能通过指定函数的测试,返回布尔值。

const arr=[2,4,6,8,10]
console.log(arr.every(value=>value%2==0))   //true

Array.some(callbackFn, thisArg)

数组中是否至少有一个元素通过了由提供的函数实现的测试。

const array = [1, 2, 3, 4, 5];
const even = (element) => element % 2 === 0;
console.log(array.some(even));// true

Array.filter(callbackFn, thisArg)

创建给定数组一部分的浅拷贝,其包含通过所提供函数实现的测试的所有元素。

const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter((word) => word.length > 6);
console.log(result);
//  ["exuberant", "destruction", "present"]

Array.find(callbackFn, thisArg)

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

const array1 = [5, 12, 8, 130, 44];
const found = array1.find((element) => element > 10);
console.log(found);     //12

Array.findIndex(callbackFn, thisArg)

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

const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// 3

Array.forEach(callbackFn, thisArg)

原数组的每个元素执行一次给定的函数。

const array1 = ['a', 'b', 'c'];
array1.forEach((element) => console.log(element));
//  "a"
//  "b"
//"c"

Array.map(callbackFn, thisArg)

创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。

const array1 = [1, 4, 9, 16];
const map1 = array1.map((x) => x * 2);
console.log(map1);//  [2, 8, 18, 32]

Array.includes(searchElement, fromIndex)

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

const array1 = [1, 2, 3];
console.log(array1.includes(2));//  trueconst pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));// true
​
console.log(pets.includes('at'));// false

Array.reduce(callbackFn, initialValue)

对数组中的每个元素按序执行一个提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。

  • callbackFn:

    • accumulator:上一次调用 callbackFn 的结果。
    • currentValue:当前元素的值。
    • currentIndex:currentValue 在数组中的索引位置。
const array1 = [1, 2, 3, 4];
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue,
);
console.log(sumWithInitial);// 10

Array.sort(compareFn)

就地对数组的元素进行排序,并返回对相同数组的引用。

默认排序是将元素转换为字符串,然后按照它们的 UTF-16 码元值升序排序。

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);//["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000];

Array.toSorted(compareFn)

它返回一个数组,其元素按升序排列。

const values = [1, 10, 21, 2];
const sortedValues = values.toSorted((a, b) => a - b);
console.log(sortedValues); // [1, 2, 10, 21]
console.log(values); // [1, 10, 21, 2]

如果觉得有用,记得收藏起来!以后遇到数组操作问题随时翻看,不用再费劲找资料了 😊