数组常用的方法
增删改查-元素
push()
在尾部追加,类似于压栈
原数组会变。
const arr = [1, 2, 3]
arr.push(8)
console.log(arr) // [1, 2, 3, 8]2
3
pop()
在尾部删除,类似于出栈
数组的 push & pop 可以模拟常见数据结构之一:栈。
原数组会变。
const arr = [1, 2, 3]
const popVal = arr.pop()
console.log(popVal) // 3
console.log(arr) // [1, 2]2
3
4
数组模拟常见数据结构之一:栈
const stack = [0, 1]
stack.push(2) // 压栈
console.log(stack) // [0, 1, 2]
const popValue = stack.pop() // 出栈
console.log(popValue) // 2
console.log(stack) // [0, 1]2
3
4
5
6
7
unshift()
在头部压入数据,类似于入队
原数组会变。
const arr = [1, 2, 3]
arr.unshift(0)
console.log(arr) // [0, 1, 2, 3]2
3
shift()
在头部弹出数据。
数组的 push(入队) & shift(出队) 可以模拟常见数据结构之一:队列。
头出尾入
原数组会变。
const arr = [1, 2, 3]
const shiftVal = arr.shift()
console.log(shiftVal) // 1
console.log(arr) // [2, 3]2
3
4
数组模拟常见数据结构之一:队列
const queue = [0, 1]
queue.push(2) // 入队
console.log(queue) // [0, 1, 2]
const shiftValue = queue.shift() // 出队
console.log(shiftValue) // 0
console.log(queue) // [1, 2]2
3
4
5
6
7
遍历迭代
forEach()
对数组中的每个元素执行一次提供的函数;
这个方法不会改变数组的长度。
对于空数组是不会执行回调函数的)
语法:array.forEach(callback(currentValue, index, arr), thisArg)
- callback(currentValue, index, arr) 必需,数组中每个元素需要调用的函数;
- currentValue 必需,当前元素;
- index 可选,当前元素的索引值;
- arr 可选,当前元素所属的数组对象;
- thisArg 可选,执行 callback 函数时使用的 this 值。
var numbers = [65, 44, 12, 4];
var temp = 0;
numbers.forEach((item) => {
return temp = temp + item
})
console.log(temp)
// 输出:1252
3
4
5
6
7
map()
按照原始数组元素顺序依次处理元素。map()方法可以方便的遍历数组。
返回一个新数组,不会改变原始数组。
// 语法:
arrayObject.map(function(currentValue,index,arr), thisValue)
// function(...) 必需,数组中的每个元素都会执行这个函数。
// currentValue (必选 当前元素的值);
// index (可选 当前元素索引)
// arr (可选 当前元素属于的数组对象。后两者在回调函数中根据是否需要来决定是否作为参数传入)。
// thisValue 可选,网上查到的说法是:对象作为该执行回调时使用,传递给函数,用作 "this" 的值。如果省略了 thisValue ,"this" 的值为 "undefined"。一般用不到该参数。2
3
4
5
6
7
8
var oldArray=[1,2,3];
var newArray=oldArray.map(function(val){
return val+=3;
});
alert(newArray); // [ 4, 5, 6 ]2
3
4
5
filter()
过滤出旧数组中符合条件的元素,存储到新数组中,筛选条件由调用方提供。
提示
filter() 不会对空数组进行检测; filter() 不会改变原始数组
语法:
array.filter(callback(currentValue,index,arr), thisArg)
- callback(currentValue, index,arr) 必需,过滤条件函数,数组中的每个元素都会执行这个函数,执行为 true 的符合筛选条件;
- currentValue 必需,当前元素的值;
- index 可选,当前元素的索引值;
- arr 可选,当前元素属于的数组对象;
- thisArg 可选,执行 callback 函数时使用的 this 值。
filter() 方法创建一个新的数组
const ages = [32, 33, 16, 40];
const newArr = ages.filter((age)=>{
return age >= 18;
});
console.log(newArr) // 输出:[32,33,40]2
3
4
5
thisArg 参数是 Array.prototype.filter() 方法的一个可选参数。它是一个值,用于指定在回调函数中作为 this 上下文执行时的上下文对象。如果没有提供 thisArg 参数,回调函数将在全局对象上作为 this 上下文执行。当你在回调函数中使用 thisArg 参数时,你实际上是在告诉 JavaScript 在执行回调函数时应该使用哪个对象作为 this 的上下文。这对于那些依赖于特定上下文的对象(如对象方法)尤其有用。
下面是一个简单的例子来帮助理解:
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(function(num) {
return this.isEven(num); // 这里假设有一个名为 isEven 的方法在 this 上
}, { isEven: function(num) { return num % 2 === 0; } });
console.log(evenNumbers); // 输出: [2, 4, 6]2
3
4
5
6
7
在这个例子中,我们假设存在一个名为 isEven 的方法,该方法用于检查一个数字是否为偶数。我们使用 thisArg 参数来指定一个对象,该对象具有一个名为 isEven 的方法。在 filter() 方法中,回调函数将在这个对象上作为 this 上下文执行,因此this.isEven(num) 将调用该对象上的 isEven 方法。
some()
some() 方法用于检测数组中的元素是否满足指定条件(函数提供)
some() 方法会为数组的每个元素依次执行 callback 函数,如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。如果没有满足条件的元素,则返回false。
some() 不会改变原始数组
提示
some() 不会对空数组进行检测。
语法:array.some(callback(currentValue,index,arr),thisArg)
参数说明:
- callback(currentValue, index,arr) 必须,函数,数组中的每个元素都会执行这个函数;
- currentValue 必须,当前元素的值;
- index 可选,当前元素的索引值;
- arr 可选,当前元素属于的数组对象;
- thisArg 可选,对象作为该执行回调时使用,传递给函数,用作 "this" 的值,如果省略了 thisArg ,"this" 的值为 "undefined"。
var ages = [3, 10, 18, 20];
function checkAdult(age) {
return age >= 18;
}
console.log(ages.some(checkAdult))
// 输出:true2
3
4
5
6
every()
every() 方法用于检测数组中所有元素是否都通过指定的测试函数;
如果数组中检测到有一个元素不满足,则整个表达式返回 false ,且剩余的元素不会再进行检测;如果所有元素都满足条件,则返回 true。
语法:array.every(callback(currentValue,index,arr), thisArg)
- callback(必需):用于测试每个元素的函数。这个函数应返回一个布尔值来指示元素是否通过测试。
- currentValue 必需,当前元素的值;
- index 可选,当前元素的索引值;
- arr 可选,当前元素属于的数组对象;
- thisArg(可选):执行 callback 函数时使用的 this 值。
- 返回值:返回一个布尔值,表示数组中的所有元素是否都通过了测试。
every() 不会改变原始数组。
提示
every() 不会对空数组进行检测。
var ages = [32, 33, 16, 40];
console.log(ages.every((item)=>item>18)) // 输出:false
console.log(ages.every((item)=>item>10)) // 输出:true2
3
find()
find() 方法查找目标数组中第一个满足条件的数组元素;
find() 方法会为数组中的每个元素依次调用一次传入的筛选条件,找到第一个满足条件的数组元素时,直接返回符合条件的元素,之后的元素不会再调用筛选函数,如果没有符合条件的元素返回 undefined。
提示
find() 对于空数组,函数是不会执行的,find() 并没有改变数组的原始值
语法:array.find(callback(currentValue, index, arr),thisArg)
- callback(currentValue, index,arr) 必需,数组每个元素需要依次执行的函数;
- currentValue 必需,当前元素;
- index 可选,当前元素的索引值;
- arr 可选,当前元素所属的数组对象;
- thisArg 可选,执行 callback 函数时使用的 this 值。
var ages = [4, 12, 16, 20];
temp = ages.find((item, index) => {
return item>= 10;
});
console.log(temp) // 输出:122
3
4
5
6
reduce()
接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce()方法可以方便的迭代数组。
不会改变原数组。
// 语法:
arrayObject.reduce(function(previousValue, currentValue, currentIndex, arr), initialValue)
// function(previousValue, currentValue, currentIndex, arr) 必需,函数,
// reduce()方法可给该回调函数传入四个值:
// previousValue (必选 上一次调用回调返回的值,或者是提供的初始(initialValue));
// currentValue (必选 数组中当前被处理的元素);
// currentIndex(可选 当前元素在数组中的索引);
// arr (可选 调用 reduce 的数组) 。
// initialValue 可选,若不设置。则初始值将变成数组中的第一项,而currentValue即从数组中的第二项开始。2
3
4
5
6
7
8
9
10
var arr = [2,4,3,7];
//数组中的元素进行累加
var val = arr.reduce(function(n1,n2) {
return n1 + n2;
},0);
console.log(val); // 162
3
4
5
6
reduceRight()
reduceRight() 方法的功能和 reduce() 功能是一样的,不同的是 reduceRight() 从数组的末尾向前将数组中的数组项做累加。
var numbers = [65, 44, 12, 4];
function getSum(total, num) {
return total + num;
}
console.log(numbers.reduce(getSum))
// 输出:125//4+12+44+652
3
4
5
6
flat()
该方法可用于:扁平化嵌套数组,扁平化与数组空项。
flat() 方法方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回,flat() 方法返回一个包含将数组与子数组中所有元素的新数组,
var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2); // [1, 2, 3, 4, 5, 6]
var arr4 = [1, 2, , 4, 5];
arr4.flat(); // [1, 2, 4, 5]2
3
4
5
flatMap()
使用映射函数映射每个元素,然后将结果压缩成一个新数组
提示
flatMap:通过 map 遍历、处理,再 flat 扁平化嵌套数组
flatMap() 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组,它与 map 连着深度值为 1 的 flat 几乎相同,但 flatMap 通常在合并成一种方法的效率稍微高一些
flatMap() 方法一个新的数组,其中每个元素都是回调函数的结果,并且结构深度 depth 值为 1。
// 箭头函数
flatMap((currentValue) => { /* … */ } )
flatMap((currentValue, index) => { /* … */ } )
flatMap((currentValue, index, array) => { /* … */ } )
// 回调函数
flatMap(callbackFn)
flatMap(callbackFn, thisArg)
// 行内回调函数
flatMap(function(currentValue) { /* … */ })
flatMap(function(currentValue, index) { /* … */ })
flatMap(function(currentValue, index, array){ /* … */ })
flatMap(function(currentValue, index, array) { /* … */ }, thisArg)2
3
4
5
6
7
8
9
10
11
12
13
14
语法: array.flatMap(callback(currentValue,index,arr), thisArg)
- callback可以生成一个新数组中的元素的函数,可以传入三个参数:
- currentValue 必需,当前正在数组中处理的元素;
- index 可选的,数组中正在处理的当前元素的索引;
- array 可选的,被调用的 map 数组;
- thisArg 可选,执行 callback 函数时 使用的this 值。
let arr1 = ["it's Sunny in", "", "California"];
arr1.map(x => x.split(" ")); // [["it's","Sunny","in"],[""],["California"]]
arr1.flatMap(x => x.split(" ")); // ["it's","Sunny","in", "", "California"]2
3
flatMap 能用于在 map 期间增删项目(也就是修改 items 的数量),换句话说,它允许你遍历很多项使之成为另一些项(靠分别把它们放进去来处理),而不是总是一对一,从这个意义上讲,它的作用类似于 filter的对立面,只需返回一个 1 项元素数组以保留该项,返回一个多元素数组以添加项,或返回一个 0 项元素数组以删除该项。
查找 / 索引 / (是否)存在
findIndex()
查找数组中第一个符合条件的元素位置
返回符合条件的元素的索引位置,之后的值不会再调用执行函数
如果没有符合条件的元素返回 -1。
findIndex() 对于空数组,函数是不会执行的;
findIndex() 不会改变数组的原始值
语法:array.findIndex(callback(currentValue, index, arr), thisArg)
- callback(currentValue, index,arr) 必须,数组每个元素需要执行的函数;
- currentValue 必需,当前元素;
- index 可选,当前元素的索引;
- arr 可选,当前元素所属的数组对象;
- thisArg 可选,执行 callback 函数时使用的 this 值。
var ages = [3, 10, 18, 20];
const temp = ages.findIndex((item, index, arr) => {
console.log(item, index, arr);
// 3 0 [ 3, 10, 18, 20 ]
// 10 1 [ 3, 10, 18, 20 ]
return item >= 10
})
console.log(temp); // 12
3
4
5
6
7
8
9
10
11
indexOf()
在数组中寻找该值,找到则返回其下标,找不到则返回-1。
const arr = [1, 2, 3]
console.log(arr.indexOf(2)) // 1
console.log(arr.indexOf(0)) // -12
3
lastIndexOf()
返回一个指定的元素在数组中最后出现的位置,从该字符串的后面向前查找
如果要检索的元素没有出现,则该方法返回 -1
该方法将从尾到头地检索数组中指定元素 item,开始检索的位置在数组的 start 处或数组的结尾(没有指定 start 参数时),如果找到一个 item,则返回 item 从尾向前检索第一个次出现在数组的位置,数组的索引开始位置是从 0 开始的,如果在数组中没找到指定元素则返回 -1。
语法:array.lastIndexOf(item,start)
- item必需,规定需检索的字符串值;
- start可选,整数参数,规定在字符串中开始检索的位置,它的合法取值是 0 到stringObject.length - 1,如省略该参数,则将从字符串的最后一个字符处开始检索。
var fruits = [1, 2, 3, 4, 2];
console.log(fruits.lastIndexOf(2)); // 4
console.log(fruits.lastIndexOf(2, 3)); // 12
3
includes()
在数组中寻找该值,找到则返回true,找不到则返回false。
const arr = [1, 2, 3]
console.log(arr.includes(2)) // true
console.log(arr.includes(4)) // false2
3
arr.at()
用于接收一个整数值,并返回该索引对应的元素,如果找不到指定的索引,则返回 undefined
接收的值 允许
正数和负数
传递 负整数
从数组中的最后一个元素开始倒数,匹配给定索引的数组中的元素
传递 非负数
此时at() 方法等价于括号表示法
例如,array[0] 和 array.at(0) 均返回第一个元素
const arr = [5, 12, 8, 130, 44];
console.log(arr.at(2)); // 8
console.log(arr.at(-2)); // 1302
3
4
其它格式(含数组)转为数组
concat()
concat会在当前数组尾部拼接传入的数组,然后返回一个新数组
原数组不变。
const arr = [1, 2, 3]
const arr2 = arr.concat([7, 8, 9])
console.log(arr) // [1, 2, 3]
console.log(arr2) // [1, 2, 3, 7, 8, 9]2
3
4
使用解构
const arr = [1, 2, 3]
const arr2 = [...arr,...[7, 8, 9]]
console.log(arr) // [1, 2, 3]
console.log(arr2) // [1, 2, 3, 7, 8, 9]2
3
4
Array.from()
从一个类似数组或可迭代对象中创建一个新的数组实例
如果对象是数组返回 true,否则返回 false;
这个方法主要用在以下几个方面:
- 从类似数组对象创建数组:当你有一个类似数组的对象(例如一个NodeList或HTMLCollection),你可以使用 Array.from() 来将它转换为真正的数组。
- 从非可迭代对象创建数组:任何可迭代对象都可以使用 Array.from() 转换为数组。例如,一个字符串、一个Map、一个Set等。
- 使用映射函数(类似map、every、forEach):Array.from() 方法允许你提供一个映射函数,该函数会在每个元素上调用,然后将结果收集到一个新数组中。
语法:Array.from(object, mapFunction, thisArg)
- object 必需,要转换为数组的对象;
- mapFunction 可选,数组中每个元素要调用的函数;
- thisArg 可选,映射函数 mapFunction 中的 this 对象。
var arr1 = Array.from([1, 2, 3], x => x * 10);
// [ 10, 20, 30 ]
var arr2 = Array.from(new Set([0, 0, 0, 1, 1, 1]));
// [ 0, 1 ]2
3
4
5
Array.of()
将一组值转换为数组,不考虑参数的数量或类型
Array.of() 和 Array() 构造函数之间的区别在于对单个参数的处理:
Array.of(7) 创建一个具有单个元素 7 的数组,
而 Array(7) 创建一个 length 为 7 的空数组,如果对象是数组返回 true,否则返回 false。
Array.of(1); // [1]
Array.of(1, 2, 3); // [1, 2, 3]
Array.of(undefined); // [undefined]2
3
keys()
从数组创建一个包含数组键的可迭代对象。
const arr = ["Banana", "Orange", "Apple", "Mango"];
const newArr = arr.keys();
for (const iterator of newArr) {
console.log(iterator);
}
// 输出:0 1 2 32
3
4
5
6
entries()
遍历数组或对象的键值对。
在数组中,entries 方法返回一个新的数组迭代器对象,该对象包含数组中每个索引的键值对。
var fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.entries());
// Object [Array Iterator] {}
console.log(Array.from(fruits.entries()));
// [
// [0, 'Banana'],
// [1, 'Orange'],
// [2, 'Apple'],
// [3, 'Mango']
// ]2
3
4
5
6
7
8
9
10
11
12
数组转为其它
join()
将数组转化成字符串,并返回该字符串,不传值则默认逗号隔开
原数组不变。
const arr = [1, 2, 3]
console.log(arr.join()) // 1,2,3
console.log(arr.join("")) // 1232
3
toString()
将数组转化成字符串,并返回该字符串,逗号隔开
原数组不变。
const arr = [1, 2, 3, 4, 5]
console.log(arr.toString()) // 1,2,3,4,5
console.log(arr.toString("")) // 1,2,3,4,5
console.log(arr) // [1, 2, 3, 4, 5]2
3
4
其它
reverse()
翻转原数组,并返回已完成翻转的数组
原数组改变。
const arr = [1, 2, 3]
console.log(arr.reverse()) // [3, 2, 1]
console.log(arr) // [3, 2, 1]2
3
slice(start,end) 截取
[ ) : 从start 开始截取到end,但是不包括end
原数组不变。
const arr = [1, 2, 3, 4, 5]
console.log(arr.slice(1, 4)) // [2, 3, 4]
console.log(arr) // [1, 2, 3, 4, 5]2
3
splice(start, deleteCount, item1, item2……) 删除-添加
start参数 开始的位置
deleteCount要删除的个数
后面的items为要添加的元素
如果deleteCount为0,则表示不删除元素,从start位置开始添加后面的几个元素到原始的数组里面。
- 返回值为
被删除的元素组成的一个数组。 - 如果只删除了一个元素,则返回
只包含一个元素的数组。 - 如果没有删除元素,则返回
空数组。
原数组改变。
const arr3 = [1, 2, 3, 4, 5, 6, 7, "f1", "f2"];
const arr4 = arr3.splice(2, 3) // 删除第三个元素以后的三个数组元素(包含第三个元素)
console.log(arr4); // [3, 4, 5];
console.log(arr3); // [1, 2, 6, 7, "f1", "f2"]; 原始数组被改变
const arr5 = arr3.splice(2, 0, "wu", "leon");
// 从第2位开始删除0个元素,插入"wu","leon"
console.log(arr5); // [] 返回空数组
console.log(arr3); // [1, 2, "wu", "leon", 6, 7, "f1", "f2"]; 原始数组被改变
const arr6 = arr3.splice(2, 3, "xiao", "long");
// 从第 2 位开始删除 3 个元素,插入"xiao", "long"
console.log(arr6); // ["wu", "leon", 6]
console.log(arr3); //[ 1, 2, "xiao", "long", 7, "f1", "f2"]
const arr7 = arr3.splice(2); // 从第三个元素开始删除所有的元素
console.log(arr7);// ["xiao", "long", 7, "f1", "f2"]
console.log(arr3); // [1, 2]2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
sort()
对数组的元素进行排序,并返回数组。
默认排序顺序是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的。
由于它取决于具体实现,因此无法保证排序的时间和空间复杂性。 可参考MDN
const arr = [1, 2, 3]
arr.sort((a, b) => b - a)
console.log(arr) // [3, 2, 1]2
3
isArray()
判断一个对象是否为数组
如果对象是数组返回 true,否则返回 false。
语法:Array.isArray(obj) 参数说明:obj 必需,要判断的对象。
const fruits = ["Banana"];
const obj = { a: 1 };
const a = 1
console.log(Array.isArray(fruits)); // true
console.log(Array.isArray(obj)); // false
console.log(Array.isArray(1)); // false2
3
4
5
6
7
fill()
将一个固定值替换数组的元素
该方法会改变原始数组
语法:array.fill(value, start, end)
- value 必需,填充的值;
- start 可选,开始填充位置;
- end 可选,停止填充位置 (默认为 array.length);
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.fill("Runoob", 2, 4)
console.log(fruits)
// 输出:['Banana', 'Orange', 'Runoob', 'Runoob']2
3
4
copyWithin()
将数组的内部元素复制到数组的其他位置,覆盖数组的原有元素,而不会改变数组的长度,是一种移动数组的高效方法。
语法:array.copyWithin(target, start, end)
- target 必需,复制到指定目标索引位置;
- start 可选,元素复制的起始位置,默认为 0;
- end 可选,停止复制的索引位置 (默认为 array.length)。如果为负值,表示倒数,从后往前数
(注:end 小于 start 时,该方法不生效)。
var arr = [1, 2, 3, 4, 5, 6];
console.log(arr.copyWithin(2, 0, 2));
// [ 1, 2, 1, 2, 5, 6 ]
var arr2 = [1, 2, 3, 4, 5, 6];
console.log(arr2.copyWithin(2, 0, -3));
// [ 1, 2, 1, 2, 3, 6 ]2
3
4
5
6
7