JavaScript数组方法42个(附示例)
- 1、at()
- 2、flat()
- 3、flatMap
- 4、join()
- 5 & 6、push() 和 pop()
- 7 & 8、shift() 和 unshift()
- 9、sort()
- 10、toSorted()
- 11、reverse()
- 12、oReversed()
- 13、concat()
- 14、slice()
- 15、splice()
- 16、toSpliced()
- 17、with()
- 18 & 19 & 20、indexOf() 和 lastIndexOf()
- 21、forEach()
- 22、map()
- 23、every()
- 24、filter()
- 25、some()
- 26、isArray()
- 27、toString()
- 28、toLocaleString()
- 29、reduce()
- 30、reduceRight()
- 31、Array.from()
- 32、Array.fromAsync()
- 33、Array.of()
- 34 & 35 & 36、find()、findIndex()、findLastIndex
- 37、fill()
- 38 & 39 & 40、entries()、values()、keys()
- 41、copyWithin()
- 42、includes()
1、at()
at()
:获取特定索引处的元素。负索引表示从末尾开始计数(例如:-1 是最后一个元素)。
const names = ["Jhon", "Bob", "Alice", "Joe"];
const nameAtIndex1 = names.at(1); // Output : Bob
const nameAtLastIndex = names.at(-1); // Output : Joe
const nameAtBeforeLastIndex = names.at(-2); // Output : Alice
const nameAtNonExistingIndex = names.at(10); // Output : undefined
2、flat()
flat()
:在每个元素中展开任何已建立的数组,并根据给定的深度级别继续展开嵌套的数组。返回新的平面数组。
const numbers = [1, 2, [3, [4, [5, 6]]]];
const flatNumbersLevel1 = numbers.flat();
console.log(flatNumbersLevel1); // Output : [1, 2, 3, [4, [5, 6]]]
const flatNumbersLevel2 = numbers.flat(2);
console.log(flatNumbersLevel2); // Output : [1, 2, 3, 4, [5, 6]]
const flatNumbers = numbers.flat(Infinity);
console.log(flatNumbers); // Output : [1, 2, 3, 4, 5, 6]
3、flatMap
flatMap
:返回一个新数组,其中所有元素均由给定回调修改,并按 1 深度级别展平。
const users = [
{name: "Jhon", votes: [3, 4] },
{name: "Joe", votes: [4, 5] }
];
const allVotes = users.flatMap((user) => user.votes);
console.log(allVotes); // Output : [3, 4, 4, 5]
4、join()
join()
:参数来拼接;分隔符
const arr = ['apple', 'banana', 'orange'];
// 使用默认分隔符(逗号)
const str1 = arr.join();
console.log(str1); //输出:'apple,banana,orange'
// 使用自定义分隔符(空格)
const str2 = arr.join(' ');
console.log(str2); // 输出:'apple banana orange'
5 & 6、push() 和 pop()
push()
:可以接受一个或者多个参数,将参数追加到数组的尾部,返回添加后的数组的长度,原数组会发生改变。
pop()
:从数组尾部删除一个元素,返回这个被删除的元素,原数组发生改变。
const arr = ['apple', 'banana', 'orange'];
// 使用 push() 方法向数组末尾添加一个元素
arr.push('grape');
console.log(arr); // 输出:['apple', 'banana', 'orange', 'grape']
// 使用 push() 方法向数组末尾添加多个元素
arr.push('kiwi', 'mango');
console.log(arr); // 输出:['apple', 'banana', 'orange', 'grape', 'kiwi', 'mango']
//------ pop ------
const arr = ['apple', 'banana', 'orange'];
const removedElement = arr.pop();
console.log(removedElement); // 输出:'orange'
console.log(arr); // 输出:['apple', 'banana']
7 & 8、shift() 和 unshift()
shift()
:删除原数组第一项,并返回删除元素的值;如果数组为空则返回undefined
unshift()
:将参数添加到原数组开头,并返回数组的长度
let arr = ["Lily","lucy","Tom"];
let count = arr.unshift("Jack","Sean");
console.log(count); // 5
console.log(arr); //["Jack", "Sean", "Lily", "lucy", "Tom"]
let item = arr.shift();
console.log(item); // Jack
console.log(arr); // ["Sean", "Lily", "lucy", "Tom"]
9、sort()
sort()
:将数组里的项从小到大排序
var arr1 = ["a", "d", "c", "b"];
console.log(arr1.sort()); // ["a", "b", "c", "d"]
sort()
方法比较的是字符串,没有按照数值的大小对数字进行排序,要实现这一点,就必须使用一个排序函数
function sortNumber(a,b) { return a - b }
arr = [13, 24, 51, 3];
console.log(arr.sort()); // [13, 24, 3, 51]
console.log(arr.sort(sortNumber)); // [3, 13, 24, 51](数组被改变)
10、toSorted()
toSorted()
:创建一个新数组,其中包含按给定回调排序的调用者数组的元素。
它类似于sort()
,但它返回一个新数组而不修改调用者数组。
const numbers = [10, 100, 20, 25, 30];
/** 按升序排序。在b之后排序a. */
const numbersInAscOrder = numbers.toSorted((a, b) => a - b); // Output : [10, 20, 25, 30, 100]
console.log(numbers); // Output : [10, 100, 20, 25, 30]
/** 按子代顺序对编号进行排序。在a之后对b排序 */
const numbersInDescOrder = numbers.toSorted((a, b) => b - a); // Output : [100, 30, 25, 20, 10]
console.log(numbers); // Output : [10, 100, 20, 25, 30]
11、reverse()
reverse()
:反转数组项的顺序
let arr = [13, 24, 51, 3];
console.log(arr.reverse()); //[3, 51, 24, 13]
console.log(arr); //[3, 51, 24, 13](原数组改变)
12、oReversed()
toReversed()
:创建一个新数组,其中,按相反顺序包含调用方数组的元素。
它类似于reverse()
,但它返回一个新数组而不修改调用者数组。
const numbers = [1, 2, 3];
const reversedNumbers = numbers.toReversed();
console.log(reversedNumbers); // Output : [3, 2, 1]
console.log(numbers); // Output : [1, 2, 3]
13、concat()
concat()
:将参数添加到原数组中。这个方法会先创建当前数组一个副本,然后将接收到的参数添加到这个副本的末尾,最后返回新构建的数组。在没有给 concat()
方法传递参数的情况下,它只是复制当前数组并返回副本。
let arr = [1,3,5,7];
let arrCopy = arr.concat(9,[11,13]);
console.log(arrCopy); //[1, 3, 5, 7, 9, 11, 13]
console.log(arr); // [1, 3, 5, 7](原数组未被修改)
14、slice()
slice()
:返回从原数组中指定开始下标到结束下标之间的项组成的新数组。slice()
方法可以接受一或两个参数,即要返回项的起始和结束位置。在只有一个参数的情况下, slice()
方法返回从该参数指定位置开始到当前数组末尾的所有项。如果有两个参数,该方法返回起始和结束位置之间的项——但不包括结束位置的项。
let arr = [1,3,5,7,9,11]; var arrCopy = arr.slice(1);
let arrCopy2 = arr.slice(1,4);
let arrCopy3 = arr.slice(1,-2);
let arrCopy4 = arr.slice(-4,-1);
console.log(arr); //[1, 3, 5, 7, 9, 11](原数组没变)
console.log(arrCopy); //[3, 5, 7, 9, 11]
console.log(arrCopy2); //[3, 5, 7]
console.log(arrCopy3); //[3, 5, 7]
console.log(arrCopy4);//[5, 7, 9]
arrCopy
只设置了一个参数,也就是起始下标为1,所以返回的数组为下标1(包括下标1)开始到数组最后。
arrCopy2
设置了两个参数,返回起始下标(包括1)开始到终止下标(不包括4)的子数组。
arrCopy3
设置了两个参数,终止下标为负数,当出现负数时,将负数加上数组长度的值(6)来替换该位置的数,因此就是从1开始到4(不包括)的子数组。
arrCopy4
中两个参数都是负数,所以都加上数组长度6转换成正数,因此相当于slice(2, 5)
。
15、splice()
splice()
:删除、插入和替换。
删除:指定2个参数:要删除的第一项的位置和要删除的项数。
let arr = [1,3,5,7,9,11];
let arrRemoved = arr.splice(0,2);
console.log(arr); //[5, 7, 9, 11]
console.log(arrRemoved); //[1, 3]
插入:可以向指定位置插入任意数量的项,只需提供 3 个参数:起始位置、 0(要删除的项数)和要插入的项。
let arrRemoved2 = arr.splice(2,0,4,6);
console.log(arr); // [5, 7, 4, 6, 9, 11]
console.log(arrRemoved2); // []
替换:可以向指定位置插入任意数量的项,且同时删除任意数量的项,只需指定 3 个参数:起始位置、要删除的项数和要插入的任意数量的项。插入的项数不必与删除的项数相等。
let arr = [1,3,5,7,9,11];
let arrRemoved = arr.splice(0,2);
console.log(arr); //[5, 7, 9, 11]
console.log(arrRemoved); //[1, 3]
16、toSpliced()
toSpliced()
:创建一个新数组,其中包含调用方数组的元素以及已替换或删除的元素。
它类似于splice()
,但它返回一个新数组而不修改调用者数组。
负索引表示从最后一个开始计数(例如:-1 是最后一个元素)。
let numbers = [1, 0, 0, 0, 1];
/** 将索引1中的元素进一步删除到3个元素([0,0,0]) */
const splicedNumbers1 = numbers.toSpliced(1, 3);// Output : [1, 1]
console.log(numbers); // Output : [1, 0, 0, 0, 1]
/** 将元素替换为索引1到索引3的2、2、2([0、0、0]) */
const splicedNumbers2 = numbers.toSpliced(1, 3, 2, 2, 2); // Output : [1, 2, 2, 2, 1]
console.log(numbers); // Output : [1, 0, 0, 0, 1]
/** 在索引1处添加元素2、2、2 */
const splicedNumbers3 = numbers.toSpliced(1, 0, 2, 2, 2); // Output : [1, 2, 2, 2, 0, 0, 0, 1]
console.log(numbers); // Output : [1, 0, 0, 0, 1]
17、with()
with()
:创建一个新数组,其中包含调用方数组的元素以及给定索引处替换的给定值。
负索引表示从最后一个开始计数(例如:-1 是最后一个元素)。
const letters = ["a", "k", "c", "d"];
/** 将索引1处的k替换为b */
console.log(letters.with(1, "b"));// Output : ["a", "b", "c", "d"]
/** 将索引-3处的k(相当于1)替换为b */
console.log(letters.with(-3, "b"));// Output : ["a", "b", "c", "d"]
18 & 19 & 20、indexOf() 和 lastIndexOf()
indexOf()
:接收两个参数:要查找的项和(可选的)表示查找起点位置的索引。其中, 从数组的开头(位置 0)开始向后查找。
lastIndexOf()
:接收两个参数:要查找的项和(可选的)表示查找起点位置的索引。其中, 从数组的末尾开始向前查找。
let arr = [1,3,5,7,7,5,3,1];
console.log(arr.indexOf(5)); //2
console.log(arr.lastIndexOf(5)); //5
console.log(arr.indexOf(5,2)); //2
console.log(arr.lastIndexOf(5,4)); //2
console.log(arr.indexOf("5")); //-1
21、forEach()
forEach()
:对数组进行遍历循环,对数组中的每一项运行给定函数。这个方法没有返回值。
参数都是 function
类型,默认有传参,
参数分别为:遍历的数组内容;第对应的数组索引,数组本身。
let arr = [1, 2, 3, 4, 5];
arr.forEach(function(x, index, a){
console.log(x + '|' + index + '|' + (a === arr));
});
// 输出为:
// 1|0|true
// 2|1|true
// 3|2|true
// 4|3|true
// 5|4|true
22、map()
map()
:指映射
,对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组。
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let arr2 = arr.map((x, index) => {
return index % 3 === 0 || x >= 8;
});
console.log(arr2); //[1, 4, 7, 8, 9, 10]
23、every()
every()
:判断数组中每一项都是否满足条件,只有所有项都满足条件,才会返回true
。
let arr = [1, 2, 3, 4, 5];
let arr2 = arr.every(x => x < 10 );
console.log(arr2); //true
let arr3 = arr.every(x => x < 3 );
console.log(arr3); // false
24、filter()
filter()
:过滤
功能,数组中的每一项运行给定函数,返回满足过滤条件组成的数组。
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let arr2 = arr.filter((x, index) => {
return index % 3 === 0 || x >= 8;
});
console.log(arr2); //[1, 4, 7, 8, 9, 10]
25、some()
some():判断数组中是否存在满足条件的项,只要有一项满足条件,就会返回true
。
let arr = [1, 2, 3, 4, 5];
let arr2 = arr.some(x => x < 3);
console.log(arr2); //true
let arr3 = arr.some(x => x < 1);
console.log(arr3); // false
26、isArray()
isArray():用于检查某个值是否为数组。它返回一个布尔值,如果给定的值是一个数组,则返回 true
,否则返回 false
。
const arr = [1, 2, 3, 4, 5];
console.log(Array.isArray(arr)); // 输出: true
const str = 'Hello';
console.log(Array.isArray(str)); // 输出: false
在上面的例子中,第一个 console.log
语句检查了变量 arr
是否为数组,由于 arr
确实是一个数组,因此 Array.isArray(arr)
返回 true
。而第二个 console.log
语句检查了变量 str
是否为数组,由于 str
是一个字符串而不是数组,因此 Array.isArray(str)
返回 false
。
isArray()
方法是一个非常有用的工具,可以帮助你在编写代码时快速检查一个值是否为数组,从而进行相应的处理。
27、toString()
toString()
:用于将数组转换为字符串。该方法会返回一个由数组元素组成的以逗号分隔的字符串。可以通过传入一个可选的参数,来指定数组元素间的分隔符。
const array = [1, 2, 3, 4, 5];
const arrayToString = array.toString();
console.log(arrayToString); // 输出: "1,2,3,4,5"
在上面的示例中,toString()
方法将数组 array
转换为了一个以逗号分隔的字符串,并将结果赋值给了变量 arrayToString
。
可以使用 join()
方法来替代 toString()
方法并指定分隔符。如果没有传入参数,则默认使用逗号作为分隔符,和 toString()
方法的行为一致。
28、toLocaleString()
toLocaleString()
:将所有元素转换为语言环境字符串,将所有元素连接为字符串,同时用逗号分隔每个元素并返回字符串。
const date = [10.4, new Date("31 Aug 2022 22:00:00 UTC")];
console.log(date.toLocaleString()); // Output : 10.4,9/1/2022, 12:00:00 AM
console.log(date.toLocaleString("en")); // Output : 10.4,9/1/2022, 12:00:00 AM
console.log(date.toLocaleString("es")); // Output : 10,4,1/9/2022, 0:00:00
29、reduce()
reduce()
:依次处理数组的每个成员,最终累计为一个值。reduce是从左到右处理(从第一个成员到最后一个成员)。
参数是一个函数,该函数接受以下两个参数:
1、累积变量,默认为数组的第一个成员;
2、当前变量,默认为数组的第二个成员。
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // 输出: 15
30、reduceRight()
reduceRight()
:用于从数组的最后一个元素开始,从右向左依次执行回调函数来累积计算。
它和reduce()
方法类似,只不过reduce()
是从左向右执行计算。
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduceRight((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // 输出: 15
31、Array.from()
用于从类数组对象或可迭代对象创建一个新的数组。
它接受一个类数组对象或可迭代对象作为第一个参数,并可选地接受一个映射函数和一个上下文对象作为参数。
基本语法:
Array.from(arrayLike[, mapFn[, thisArg]])
arrayLike
: 必需,要转换为数组的类数组对象或可迭代对象。
mapFn
: 可选,映射函数,用来对数组中的每个元素进行处理。
thisArg
: 可选,映射函数中的 this
值。
let json ={
'0':'hello',
'1':'123',
'2':'panda',
length:3
}
let arr = Array.from(json); console.log(arr);
//打印:["hello", "123", "panda"]
// 从字符串创建数组
const str = 'hello';
const strArray = Array.from(str);
console.log(strArray); // 输出: ["h", "e", "l", "l", "o"]
// 从类数组对象创建数组
const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 };
const arrayFromObj = Array.from(arrayLike);
console.log(arrayFromObj); // 输出: ["a", "b", "c"]
// 使用映射函数
const squares = Array.from([1, 2, 3], x => x * x);
console.log(squares); // 输出: [1, 4, 9]
32、Array.fromAsync()
fromAsync()
:从异步可迭代、可迭代或类数组创建数组。
/** Create an array from an array of async elements */
const asyncArray = [
new Promise((resolve) => resolve(0)),
new Promise((resolve) => resolve(1))
];
(async () => {
const array = await Array.fromAsync(asyncArray);
console.log(array); // Output : [0, 1]
})();
33、Array.of()
将一组值转变为数组
let arr1 = Array.of('你好','hello');
console.log(arr1); // ["你好", "hello"]
34 & 35 & 36、find()、findIndex()、findLastIndex
用于找出第一个符合条件的数组成员。参数是个回调函数,所有数组成员依次执行该回调函数,直到找到第一个返回值为true
的成员,然后返回该成员。如果没有符合条件的成员,就返回undefined
;
可以接收3个参数,依次为当前值、当前位置、原数组。
const numbers = [1, 2, 3, 4, 5];
const foundNumber = numbers.find(function(element) {
return element > 3;
});
console.log(foundNumber); // 输出: 4
const foundIndex = numbers.findIndex(function(element) {
return element > 3;
});
console.log(foundIndex); // 输出: 3
findLastIndex()
:找到最后一个验证条件的元素并返回其索引。否则,返回-1。
const names = ["Joe", "Jhon", "Alice"];
const lastNameMatchStartWithJ = names.findLastIndex((name) => name.startsWith("J"));
console.log(lastNameMatchStartWithJ); // Output : 1
const lastNameMatchStartWithK = names.findLastIndex((name) => name.startsWith("K"));
console.log(lastNameMatchStartWithK); // Output : -1
37、fill()
使用fill()
方法给定值填充数组。
可以接收第二个和第三个参数,用于指定填充的起始位置和结束位置(不包括结束位置)
let arr3 = [0,1,2,3,4,5,6,7]; arr3.fill('error',2,3);
console.log(arr3); // [0, 1, "error", 3, 4, 5, 6, 7]
38 & 39 & 40、entries()、values()、keys()
遍历数组的方法:entries()
、values()
、keys()
for(let item of ['a','b'].keys()){
consloe.log(item);
//0
//1
}
for(let item of ['a','b'].values()){
consloe.log(item);
//'a'
//'b'
}
let arr4 = [0,1];
for(let item of arr4.entries()){
console.log(item);
// [0, 0]
// [1, 1]
}
如果不用for...of
进行遍历,可用使用next()
方法手动跳到下一个值。
let arr5 =['a','b','c']
let entries = arr5.entries();
console.log(entries.next().value); // [0, "a"]
console.log(entries.next().value); // [1, "b"]
console.log(entries.next().value); // [2, "c"]
console.log(entries.next().value); // undefined
41、copyWithin()
在数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),改变原数组。
该函数有三个参数:
target
:目的起始位置。
start
:复制源的起始位置(从0开始),可以省略,可以是负数。
end
:复制源的结束位置,可以省略,可以是负数,实际结束位置是end-1。
const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
arr1.copyWithin(1, 3, 6);
// 把第3个元素(从0开始)到第5个元素,复制并覆盖到以第1个位置开始的地方。
console.log('%s', JSON.stringify(arr1))
// [1, 4, 5, 6, 5, 6, 7, 8, 9, 10, 11]
start和end都是可以省略。start省略表示从0开始,end省略表示数组的长度值。目标的位置不够的,能覆盖多少就覆盖多少。
const arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
arr2.copyWithin(3)
console.log('%s', JSON.stringify(arr2))
//[1, 2, 3, 1, 2, 3, 4, 5, 6, 7, 8]
start和end都可以是负数,负数表示从右边数过来第几个(从-1开始)。start小于end,两者为负数时也是。
const arr3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
arr3.copyWithin(3, -3, -2)
console.log('%s', JSON.stringify(arr3))
end永远大于start(取值必须是start右边的),end小于start(取start左边的值)时会返回原数组。
42、includes()
表示某个数组是否包含给定的值,如果包含则返回 true
,否则返回false
。
可以接收两个参数:要搜索的值和搜索的开始索引。当第二个参数被传入时,该方法会从索引处开始往后搜索(默认索引值为0)。
若搜索值在数组中存在则返回true
,否则返回false
。
['a', 'b', 'c', 'd'].includes('b') // true
['a', 'b', 'c', 'd'].includes('b', 1) // true
['a', 'b', 'c', 'd'].includes('b', 2) // false
tips:includes()
与indexOf()
的区别是:前者返回布尔值(利于if
条件判断),后者返回数值。