常用常见数组方法整理大全(绝对详细)!!!

前言
js的数组方法是真的多,整理一下,以供参考

join

将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串,用指定的分隔符字符串分隔。如果数组只有一个元素,那么将返回该元素而不使用分隔符。

ex:

join(separator)

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"
  • 如果一个元素是 undefinednull,它将被转换为空字符串,而不是字符串 "undefined""null"!
concat

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

ex:

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"]
  • 是对所有被合并数组的浅拷贝
slice

返回一个[start,end)的原数组的浅拷贝,不改变原数组

ex:

slice(start, 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"]

console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]

console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

  • 是对原数组的浅拷贝
splice(改变原数组)

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

ex:

splice(start, deleteCount, item1, item2, /* …, */ itemN)
//在第start位,删去deleteCount个元素,插入itemN元素
//start必选,其余可选

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"]
reverse(改变原数组)

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

ex:

const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// Expected output: "array1:" Array ["one", "two", "three"]

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

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// Expected output: "array1:" Array ["three", "two", "one"]
  • 返回的是对原数组的引用
sort(改变原数组)

就地对数组的元素进行排序,并返回对相同数组的引用。默认排序是将元素转换为字符串,然后按照它们的 UTF-16 码元值升序排序。

ex:

sort(compareFn)
//compareFn:排序函数

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// Expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// Expected output: Array [1, 100000, 21, 30, 4]

  • 比较规则

    在这里插入图片描述

toString

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

ex:

const array1 = [1, 2, 'a', '1a'];

console.log(array1.toString());
// Expected output: "1,2,a,1a"

  • Array 对象覆盖了 ObjecttoString 方法。数组的 toString 方法实际上在内部调用了 join() 方法来拼接数组并返回一个包含所有数组元素的字符串,元素之间用逗号分隔。如果 join 方法不可用或者不是函数,则会使用 Object.prototype.toString 来代替,并返回 [object Array]
indexOf

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

ex:

indexOf(searchElement, fromIndex)
//fromIndex:开始搜索的索引(从零开始)

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
  • indexOf() 使用严格相等(与 === 运算符使用的算法相同)将 searchElement 与数组中的元素进行比较。NaN 值永远不会被比较为相等,因此当 searchElementNaNindexOf() 总是返回 -1
lastIndexOf

返回数组中给定元素最后一次出现的索引,如果不存在则返回 -1。该方法从 fromIndex 开始向前搜索数组。

ex:

lastIndexOf(searchElement, fromIndex)
//从 fromIndex 开始向前搜索数组

const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

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

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

对数组的每个元素执行一次给定的函数,返回undefined,不改变原数组

forEach(callbackFn(currentValue[,index,array])[,thisArg])

const array1 = ['a', 'b', 'c'];

array1.forEach((element) => console.log(element));

// Expected output: "a"
// Expected output: "b"
// Expected output: "c"
  • forEach() 总是返回 undefined,即丢弃每次函数的返回值
  • 一旦执行,除非抛出异常,否则无法中断
  • 期待同步函数,不会等待Promise兑现
map

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

map(callbackFn, thisArg)
//参数列表同forEach

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]
  • 不在稀疏数组空槽处调用
filter

过滤数组元素,返回一个包含所有通过测试的元素的浅拷贝

filter(callbackFn, thisArg)

const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter((word) => word.length > 6);

console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]
  • 如果没有元素通过测试,则返回一个空数组。
  • 不在稀疏数组空槽处调用
every

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

是否都是

every(callbackFn, thisArg)
//每次回调函数都返回true则为true,否则false

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// Expected output: true

  • 不在稀疏数组空槽处调用
some

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

如果在数组中找到一个元素使得提供的函数返回 true,则返回 true;否则返回 false。它不会修改数组。

是否存在

some(callbackFn, thisArg)

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
  • 为数组中的每个元素调用一次指定的 callbackFn 函数,直到 callbackFn 返回一个真值
at

接收一个整数值并返回该索引对应的元素

at(index)

const array1 = [5, 12, 8, 130, 44];

let index = 2;

console.log(`An index of ${index} returns ${array1.at(index)}`);
// Expected output: "An index of 2 returns 8"

index = -2;

console.log(`An index of ${index} returns ${array1.at(index)}`);
// Expected output: "An index of -2 returns 130"

  • 为什么?

    在传递非负数时,at() 方法等价于括号表示法。例如,array[0]array.at(0) 均返回第一个元素。但是,当你需要从数组的末端开始倒数时,则不能使用 Python 和 R 语言中支持的 array[-1],因为方括号内的所有值都会被视为字符串属性,因此你最终读取的是 array["-1"],这只是一个普通的字符串属性而不是数组索引。

reduce

对数组进行一个累积的操作

reduce(callbackFn, initialValue)
//初始值可以是number,也可以array,object等
//操作应是对初始值进行累计的操作,每次操作完成后需要返回给下次操作

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue,
);

console.log(sumWithInitial);
// Expected output: 10
  • 当开始调用 reduce() 时,callbackFn 将不会访问超出数组初始长度的任何元素。
  • 对已访问索引的更改不会导致再次在这些元素上调用 callbackFn
  • 如果数组中一个现有的、尚未访问的元素被 callbackFn 更改,则它传递给 callbackFn 的值将是该元素被修改后的值。被删除的元素则不会被访问。

边界情况

  • 提供初始值,且数组长度为0,直接返回初始值,不调用回调函数
  • 不提供初始值,且数组长度为1,同上
  • 不提供初始值,且数组长度为0,抛出TypeError
find

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

find(callbackFn, thisArg)
//callbackFn返回true代表此元素通过测试

const array1 = [5, 12, 8, 130, 44];

const found = array1.find((element) => element > 10);

console.log(found);
// Expected output: 12

  • 当调用 find() 时,callbackFn 不会访问超出数组初始长度的任何元素。
  • 对已经访问过的索引的更改不会导致再次在这些元素上调用 callbackFn
  • 如果 callbackFn 改变了数组中已存在但尚未被访问的元素,则传递给 callbackFn 的该元素的值将是该元素在被访问时的值。被删除的元素被视为 undefined
findIndex

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

findIndex(callbackFn, thisArg)

const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// Expected output: 3

  • 当调用 findIndex() 时,callbackFn 不会访问超出数组初始长度的任何元素。
  • 对已经访问过的索引的更改不会导致再次在这些元素上调用 callbackFn
  • 如果 callbackFn 改变了数组中已存在但尚未被访问的元素,则传递给 callbackFn 的该元素的值将是该元素在被访问时的值。被删除的元素被视为 undefined
push&&pop

在数组末尾推入/删除元素,删除时返回该元素的值

shift&&unshift

在数组开头删去/插入元素,删除时返回该元素的值

includes

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

includes(searchElement, fromIndex)

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
toLocaleString

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

根据当地环境转为字符串

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

console.log(localeString);
// Expected output: "1,a,12/21/1997, 2:12:00 PM"
entries

返回一个新的数组迭代器对象,该对象包含数组中每个索引的键/值对

const array1 = ['a', 'b', 'c'];

const iterator1 = array1.entries();

console.log(iterator1.next().value);
// Expected output: Array [0, "a"]

console.log(iterator1.next().value);
// Expected output: Array [1, "b"]
const a = ["a", "b", "c"];

for (const [index, element] of a.entries()) {
  console.log(index, element);
}

// 0 'a'
// 1 'b'
// 2 'c'
values

返回一个新的数组迭代器对象,该对象迭代数组中每个元素的

const array1 = ['a', 'b', 'c'];
const iterator = array1.values();

for (const value of iterator) {
  console.log(value);
}

// Expected output: "a"
// Expected output: "b"
// Expected output: "c"
Array.prototype.values === Array.prototype[Symbol.iterator]; // true

const arr = ["a", "b", "c", "d", "e"];
const iterator = arr.values();
iterator.next(); // { value: "a", done: false }
iterator.next(); // { value: "b", done: false }
iterator.next(); // { value: "c", done: false }
iterator.next(); // { value: "d", done: false }
iterator.next(); // { value: "e", done: false }
iterator.next(); // { value: undefined, done: true }
console.log(iterator.next().value); // undefined
  • 如果使用 break 语句提前结束迭代,当继续迭代时,迭代器可以从当前位置恢复迭代。
  • values() 返回的可迭代对象是不可重复使用的。当 next().done = truecurrentIndex > length 时,for...of 循环结束,进一步迭代它没有任何效果。
keys

返回一个新的数组迭代器对象,其中包含数组中每个元素的

const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();

for (const key of iterator) {
  console.log(key);
}

// Expected output: 0
// Expected output: 1
// Expected output: 2
Array.prototype[Symbol.iterator]()

Array.prototype.values === Array.prototype[Symbol.iterator]; // true

for…of&&for…in

  • 用途不同:
    for…in循环用于遍历对象的属性。
    for…of循环用于遍历可迭代对象(如数组,字符串,Set,Map等)的值。
  • 遍历的内容不同:
    for…in会遍历对象所有的可枚举属性,包括原型链上的属性。
    for…of遍历的是可迭代对象的实际值,不包括原型链上的值。
  • 循环控制不同:
    for…in循环使用对象的属性名作为循环变量的值。
    for…of循环使用迭代器的值作为循环变量的值。
flat

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

flat(depth)
//depth为几就展开几层的子数组元素,默认1

const arr1 = [0, 1, 2, [3, 4]];

console.log(arr1.flat());
// expected output: Array [0, 1, 2, 3, 4]

const arr2 = [0, 1, [2, [3, [4, 5]]]];

console.log(arr2.flat());
// expected output: Array [0, 1, 2, Array [3, Array [4, 5]]]

console.log(arr2.flat(2));
// expected output: Array [0, 1, 2, 3, Array [4, 5]]

console.log(arr2.flat(Infinity));
// expected output: Array [0, 1, 2, 3, 4, 5]
fill(改变原数组)

用一个固定值填充一个数组中从起始索引(默认为 0)到终止索引(默认为 array.length)内的全部元素。它返回修改后的数组。

fill(value, start, end)

const array1 = [1, 2, 3, 4];

// Fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// Expected output: Array [1, 2, 0, 0]

// Fill with 5 from position 1
console.log(array1.fill(5, 1));
// Expected output: Array [1, 5, 5, 5]

console.log(array1.fill(6));
// Expected output: Array [6, 6, 6, 6]
  • 在一个空数组(length = 0)上使用 Array.prototype.fill() 不会对其进行修改
  • fill() 是个修改方法,不会改变 this 的长度,但会改变 this 的内容。

参考:MDN

fill(value, start, end)

const array1 = [1, 2, 3, 4];

// Fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// Expected output: Array [1, 2, 0, 0]

// Fill with 5 from position 1
console.log(array1.fill(5, 1));
// Expected output: Array [1, 5, 5, 5]

console.log(array1.fill(6));
// Expected output: Array [6, 6, 6, 6]
  • 在一个空数组(length = 0)上使用 Array.prototype.fill() 不会对其进行修改
  • fill() 是个修改方法,不会改变 this 的长度,但会改变 this 的内容。

参考:MDN

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值