JS数组方法整理
以下是JS数组方法的整理,按照功能对其进行了一下分类整理。
Array.of、Array.from、Array.isArray、Array.at、valueOf
- Array.of:创建一个具有可变数量参数的新数组,而不考虑参数的数量或类型。
Array.of(8); // [8]
Array.of(1, 2, 3); // [1, 2, 3]
- Array.from:对一个类似数组或可迭代对象创建一个新的,浅拷贝的数组。
function arga(...args) { //...args剩余参数数组,由传递给函数的实际参数提供
let arg = Array.from(args);
console.log(arg);
}
arga('arr1', 26, 'from'); // ['arr1', 26, 'from']
- Array.isArray:用于确定某个值是否是一个数组。
Array.isArray([1, 2, 3, 4, 5]); // true
Array.isArray(5); // false
- Array.at:接收一个整数值并返回该索引的值,允许正数和负数。
const list = [1, 2, 3, 4, 5];
list.at(1); // 2
list.at(-1); // 5
list.at(-2); // 4
- valueOf:返回数组的原始值(一般情况下其实就是数组自身),一般由js在后台调用,并不显式的出现在代码中。
const str = [1, 2, 3];
console.log(str.valueOf()); // [1, 2, 3]
console.log(str); // [1, 2, 3]
//为了证明返回的是数组自身
console.log(str.valueOf() == str); // true
toString、toLocaleString、join
- toString 、toLocaleString:将数组转换成字符串,类似于没有参数的join()。
const array = [1, 2, 3, 4];
const str1 = array.toString();
const str2 = array.toLocaleString();
console.log(str1); // 1,2,3,4
console.log(str2); // 1,2,3,4
- join:用指定的分隔符将数组每一项拼接为字符串。(元素是通过指定的分隔符进行分隔的。默认使用逗号作为分隔符。)
const arr = [1, 2, 3];
console.log(arr.join()); // 1,2,3
console.log(arr.join("-")); // 1-2-3
console.log(arr); // [1, 2, 3]
concat、slice
- concat:用于连接两个或多个数组。
const arr = [1, 2, 3];
const arrCopy1 = arr.concat(4, 5, 6);
const arrCopy2 = arr.concat(4, [5, 6]);
const arrCopy3 = arr.concat([4, [5, 6]]);
console.log(arr); // [1, 2, 3](原数组未被修改)
console.log(arrCopy1); // [1, 2, 3, 4, 5, 6]
console.log(arrCopy2); // [1, 2, 3, 4, 5, 6]
console.log(arrCopy3); // [1, 2, 3, 4, [5, 6]]
- slice:用于数组截取,返回从原数组中指定开始下标到结束下标之间的项组成的新数组。(左闭右开)
const arr = [1, 3, 5, 7, 9, 11];
const arrCopy1 = arr.slice(1);
const arrCopy2 = arr.slice(1, 4);
const arrCopy3 = arr.slice(1, -2);
const arrCopy4 = arr.slice(-4, -1);
console.log(arr); // [1, 3, 5, 7, 9, 11](原数组没变)
console.log(arrCopy1); // [3, 5, 7, 9, 11]
console.log(arrCopy2); // [3, 5, 7]
console.log(arrCopy3); // [3, 5, 7]
console.log(arrCopy4); // [5, 7, 9]
includes
- includes:用于判断一个数组是否包含一个指定的值
const array = [1, 3, 5, 7, 9, 11];
const includes1 = array.includes(3);
console.log(includes1); // true
const includes2 = array.includes(3, 3); // 从索引3开始查找3是否存在
console.log(includes2); // false
pop、shift、unshift、push、reverse、sort、splice
注意:此七个方法会改变原数组,其它一律不会改变原数组。
- push:向数组末尾添加元素,可以添加一个或多个元素,并返回新的长度。
- pop:删除数组的最后一个元素并返回删除的元素。
const arr = ["Lily","lucy","Tom"];
const count = arr.push("Jack","Sean");
console.log(count); // 5
console.log(arr); // ["Lily", "lucy", "Tom", "Jack", "Sean"]
const item = arr.pop();
console.log(item); // Sean
console.log(arr); // ["Lily", "lucy", "Tom", "Jack"]
- unshift:向数组开头添加元素,可以添加一个或多个元素,并返回新的长度。
- shift:删除数组的第一个元素并返回删除的元素。
const arr = ["Lily","lucy","Tom"];
const count = arr.unshift("Jack","Sean");
console.log(count); // 5
console.log(arr); // ["Jack", "Sean", "Lily", "lucy", "Tom"]
const item = arr.shift();
console.log(item); // Jack
console.log(arr); // ["Sean", "Lily", "lucy", "Tom"]
- reverse:数组反转,用于颠倒数组中元素的顺序。
const array1 = [22, 3, 31, 12];
array1.reverse();
console.log(array1); // [12, 31, 3, 22]
- sort:数组排序,用于对数组的元素进行排序。
const arr = [1,100,5,20];
console.log(arr.sort()); // [1, 100, 20, 5]
console.log(arr); // [1, 100, 20, 5] (原数组改变)
请注意,上面的代码没有按照数值的大小对数字进行排序,是按照字符编码的顺序进行排序,要实现这一点,就必须使用一个排序函数
升序:
const arr = [1,100,5,20];
function sortNumber(a,b){return a - b};
console.log(arr.sort(sortNumber)); // [1, 5, 20, 100]
console.log(arr); // [1, 5, 20, 100] (原数组改变)
降序:
const arr = [1,100,5,20];
function sortNumber(a,b){return b - a};
console.log(arr.sort(sortNumber)); // [100, 20, 5, 1]
console.log(arr); // [100, 20, 5, 1] (原数组改变)
- splice:数组更新,向/从数组中添加/删除项目,然后返回被删除的项目。
const arr= ["张三","李四","王五","小明","小红"];
/**************删除"王五"****************/
const arrReplace1 = arr.splice(2,1);
console.log(arrReplace1); // ["王五"]
console.log(arr); // ["张三", "李四", "小明", "小红"] (原数组改变)
//删除多个
const arrReplace2 = arr.splice(1,2);
console.log(arrReplace2); // ["李四", "小明"]
console.log(arr); // ["张三", "小红"]
/**************添加"小刚"****************/
const arrReplace3 = arr.splice(1,0,"小刚");
console.log(arrReplace3); // [] (没有删除元素,所以返回的是空数组)
console.log(arr); // ["张三", "小刚", "小红"]
//添加多个
const arrReplace4 = arr.splice(3,0,"刘一","陈二","赵六");
console.log(arrReplace4); // []
console.log(arr); // ["张三", "小刚", "小红", "刘一", "陈二", "赵六"]
/**************"王五"替换"小刚"****************/
const arrReplace5 = arr.splice(1,1,"王五");
console.log(arrReplace5); // ["小刚"]
console.log(arr); // ["张三", "王五", "小红", "刘一", "陈二", "赵六"]
//替换多个
const arrReplace6 = arr.splice(1,4,"李四");
console.log(arrReplace6); // ["王五", "小红", "刘一", "陈二"]
console.log(arr); // ["张三", "李四", "赵六"]
indexOf、lastIndexOf、find、findIndex、findLast、findLastIndex
-
indexOf:从数组的开头(位置 0)开始向后查找,返回要查找的项在数组中首次出现的位置,在没找到的情况下返回-1。
indexOf()--------array.indexOf(item,start)
item: 必须。查找的元素。
start:可选的整数参数。规定在数组中开始检索的位置。如省略该参数,则将从array[0]开始检索。 -
lastIndexOf:从数组的末尾开始向前查找,返回要查找的项在数组中首次出现的位置,在没找到的情况下返回-1。
lastIndexOf()--------array.lastIndexOf(item,start)
item: 必须。查找的元素。
start:可选的整数参数。规定在数组中开始检索的位置。如省略该参数,则将从 array[array.length-1]开始检索。
const arr = [1,4,7,10,7,18,7,26];
console.log(arr.indexOf(7)); // 2
console.log(arr.lastIndexOf(7)); // 6
console.log(arr.indexOf(7,4)); // 4
console.log(arr.lastIndexOf(7,2)); // 2
console.log(arr.indexOf(5)); // -1
- find:从数组的第一个成员开始,依次向后检查,返回匹配的值。
- findIndex:从数组的第一个成员开始,依次向后检查,返回匹配位置的索引。
find()与findIndex()方法均接受两个参数:一个回调函数,一个可选值用于指定回调函数内部的this。
回调函数可接受三个参数:数组的某个元素,该元素对应的索引位置,以及该数组本身。
该回调函数应当在给定的元素满足你定义的条件时返回true,而find()和findIndex()方法均会在回调函数第一次返回true时停止查找。
const arr = [1, 2, 3, 'arr', 5, 1, 9];
console.log(arr.find((value, keys, arr) => {
return value > 2;
})); // 3 返回匹配的值
console.log(arr.findIndex((value, keys, arr) => {
return value > 2;
})); // 2 返回匹配位置的索引
- findLast:从数组的最后一个成员开始,依次向前检查,返回匹配的值。
- findLastIndex:从数组的最后一个成员开始,依次向前检查,返回匹配位置的索引。
const arr = [1, 2, 3, 'arr', 5, 1, 9];
console.log(arr.findLast((value, keys, arr) => {
return value > 2;
})); // 9 返回匹配的值
console.log(arr.findLastIndex((value, keys, arr) => {
return value > 2;
})); // 6 返回匹配位置的索引
forEach、map、filter、every、some
- forEach:对数组进行遍历循环,没有返回值。
语法:array.forEach(function(currentValue , index , arr){//do something}, thisValue)
currentValue : 必需。当前元素
index: 可选。当前元素的索引值。
arr : 可选。当前元素所属的数组对象。
thisValue: 可选。传递给函数的值一般用 “this” 值。如果这个参数为空, “undefined” 会传递给 “this” 值
const Arr = [1,4,7,10];
Arr.forEach(function(currentValue, index, arr){
console.log(index+"--"+currentValue+"--"+(arr === Arr));
})
// 输出:
// 0--1--true
// 1--4--true
// 2--7--true
// 3--10--true
- map:对数组进行遍历循环,“映射”,返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
语法:array.map(function(currentValue , index , arr){//do something}, thisValue)
const arr1 = [1,4,8,10];
const arr2 = arr1.map(function(currentValue){
return currentValue*currentValue;
});
console.log(arr2); // [1, 16, 64, 100]
- filter:对数组进行遍历循环,“过滤”,返回一个新数组,其包含通过所提供函数实现的测试的所有元素。
语法: array.filter(function(currentValue , index , arr){//do something}, thisValue)
const arr = [1,4,6,8,10];
const result1 = arr.filter(function(currentValue){
return currentValue>5;
});
console.log(result1); // [6, 8, 10]
const result2 = arr.filter(function(currentValue){
return currentValue>"5";
});
console.log(result2); // [6, 8, 10]
注意:当我们分别设置item > 5和item > "5"时, 返回的结果是一样的,由此我们可以看出函数支持弱等于(==),不是必须全(===)。
- every:判断数组中每一项都是否满足条件,只有所有项都满足条件,才会返回true。
语法: array.every(function(currentValue , index , arr){//do something}, thisValue)
const arr = [1,4,6,8,10];
const result1 = arr.every(function(currentValue){
return currentValue< 12;
});
console.log(result1); // true
const result2 = arr.every(function(currentValue){
return currentValue> 1;
});
console.log(result2); // false
- some:判断数组中是否存在满足条件的项,只要有一项满足条件,就会返回true。
语法: array.some(function(currentValue , index , arr){//do something}, thisValue)
const arr = [1,4,6,8,10];
const result1 = arr.some(function(currentValue){
return currentValue> 10;
});
console.log(result1); // false
const result2 = arr.some(function(currentValue){
return currentValue> 5;
});
console.log(result2); // true
keys、values、entries
- keys、values、entries:遍历数组方法
唯一区别:
keys()是对键名的遍历、values()对键值的遍历、entries()是对键值对的遍历
keys():
let arr = ["a","b","c","d"];
for(let i of arr.keys()){
console.log(i);
}
//打印:
// 0
// 1
// 2
// 3
values():
let arr = ["a","b","c","d"];
for(let i of arr.values()){
console.log(i);
}
//打印:
// a
// b
// c
// d
entries():
let arr = ["a","b","c","d"];
for(let i of arr.entries()){
console.log(i);
}
//打印:
// [0, "a"]
// [1, "b"]
// [2, "c"]
// [3, "d"]
for(let [idx,item] of arr.entries()){
console.log(idx+":"+item);
}
//打印:
// 0:a
// 1:b
// 2:c
// 3:d
额外知识点补充:
for...in 循环对象可以是数组,也可以是对象(遍历key值)
for...of 循环对象是数组(遍历value值)
例子:
const arr1 = [11,22,33];
const arr2=[{name:'aa',age:12},{name:'bb',age:13},{name:'cc',age:14}];
const obj = {
name: '张三',
age: 18,
action: {
123: '123',
456: '456'
}
}
for(let i in arr1){console.log(i)} // 打印:0,1,2
for(let i in arr2){console.log(i)} // 打印:0,1,2
for(let i in obj){console.log(i)} // 打印:name,age,action
for(let i of arr1){console.log(i)} // 打印:11,22,33
for(let i of arr2){console.log(i)} // 打印:{name:'aa',age:12},{name:'bb',age:13},{name:'cc',age:14}
for(let i of obj){console.log(i)} // 报错:Uncaught TypeError: obj is not iterable
reduce、reduceRight
这两个方法都会实现迭代数组的所有项(即累加器),然后构建一个最终返回的值。
- reduce:从数组的第一项开始,逐个遍历到最后。
reduce()语法:arr.reduce(function(total , cur , index , arr){//do something}, initialValue) - reduceRight:从数组的最后一项开始,向前遍历到第一项。
reduceRight()语法:arr.reduceRight(function(total , cur , index , arr){//do something}, initialValue)
total :必需。初始值, 或者计算结束后的返回值。
cur :必需。当前元素。
index :可选。当前元素的索引。
arr:可选。当前元素所属的数组对象。
initialValue:可选。传递给函数的初始值。
const arr = [1,2,3,4,5];
const result1 = arr.reduce(function(total,cur,index,arr){
console.log("total:"+total+",cur:"+cur+",index:"+index);
return total+cur;
});
console.log("结果:"+result1);
// 输出
// total:1,cur:2,index:1
// total:3,cur:3,index:2
// total:6,cur:4,index:3
// total:10,cur:5,index:4
// 结果:15
const result2 = arr.reduce(function(total,cur,index,arr){
console.log("total:"+total+",cur:"+cur+",index:"+index);
return total+cur;
},10);
console.log("结果:"+result2);
// 输出
// total:10,cur:1,index:0
// total:11,cur:2,index:1
// total:13,cur:3,index:2
// total:16,cur:4,index:3
// total:20,cur:5,index:4
// 结果:25
flat、flatMap
- flat:方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// [0, 1, 2, 3, 4]
const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2));
// [0, 1, 2, [3, 4]]
//使用 Infinity,可展开任意深度的嵌套数组
const arr3 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
console.log(arr3.flat(Infinity));
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// 扁平化数组空项,如果原数组有空位,flat()方法会跳过空位
var arr4 = [1, 2, , 4, 5];
console.log(arr4.flat());
// [1, 2, 4, 5]
- flatMap:方法会对原数组的每个成员执行一个函数,相当于执行Array.prototype.map(),然后对返回值组成的数组执行flat()方法。
// 相当于 [[2, 4], [3, 6], [4, 8]].flat()
[2, 3, 4].flatMap((x) => [x, x * 2])
// [2, 4, 3, 6, 4, 8]
fill
- fill:用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。(左闭右开)
语法:array.fill(value, start, end)
value:必需。填充的值。
start:可选。开始填充位置。如果这个参数是负数,那么它规定的是从数组尾部开始算起。
end:可选。停止填充位置 (默认为 array.length)。如果这个参数是负数,那么它规定的是从数组尾部开始算起。
let arr = [1,2,3,4,5,6];
arr.fill(0); // [0, 0, 0, 0, 0, 0]
arr.fill(0,1); // [1, 0, 0, 0, 0, 0]
arr.fill(0,1,2); // [1, 0, 3, 4, 5, 6]
arr.fill(0,-1); // [1, 2, 3, 4, 5, 0]
arr.fill(0,1,-1); // [1, 0, 0, 0, 0, 6]
copyWithin
- copyWithin:用于从数组的指定位置拷贝元素到数组的另一个指定位置中,会覆盖原有成员。
语法:array.copyWithin(target , start , end)
target :必需。从该位置开始替换数据。
start :可选。从该位置开始读取数据,默认为 0 。如果为负值,表示倒数。
end: 可选。到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数。
let arr= [1,2,3,4,5,6];
let result1 = [1,2,3,4,5,6].copyWithin(0);
let result2 = [1,2,3,4,5,6].copyWithin(0,1);
let result3 = [1,2,3,4,5,6].copyWithin(1,3,5);
let result4 = [1,2,3,4,5,6].copyWithin(1,2,-1);
let result5 = [1,2,3,4,5,6].copyWithin(1,-4,6);
console.log(result1); // [1, 2, 3, 4, 5, 6]
console.log(result2); // [2, 3, 4, 5, 6, 6]
console.log(result3); // [1, 4, 5, 4, 5, 6]
console.log(result4); // [1, 3, 4, 5, 5, 6]
console.log(result5); // [1, 3, 4, 5, 6, 6]