前端常用数组操作

177 阅读8分钟

从头部插入

unshift()

定义:unshift() 方法可向数组的开头添加一个或更多元素,并返回新的长度。

参数:item1, item2, ..., itemX ,要添加到数组开头的元素。

示例

let arr = [1, 2, 3]; 
arr.unshift(4,5,6);    // 6
// arr: [4, 5, 6, 1, 2, 3]

从尾部插入

push()

定义:push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度。

参数:item1, item2, ..., itemX ,要添加到数组末尾的元素。

示例

let arr = [1, 2, 3];
arr.push(4,5,6);    // 6
// arr: [1, 2, 3, 4, 5, 6]

concat()

定义: 方法用于合并两个或多个数组,返回一个新数组。

语法: var newArr = oldArray.concat(arrayX,arrayX,......,arrayX);

参数:该参数可以是具体的值,也可以是数组对象。可以是任意多个。

示例

let a = [1, 2, 3];  
let b = [4, 5, 6];  
// 连接两个数组  
let newArr = a.concat(b);    // [1, 2, 3, 4, 5, 6]  
// 连接3个数组  
let c = [7, 8, 9];  
let newArr2 = a.concat(b,c);    // [1, 2, 3, 4, 5, 6, 7, 8, 9]  
// 添加元素  
let newArr3 = a.concat('元素1',b,c,'元素2');    // [1, 2, 3, '元素1', 4, 5, 6, 7, 8, 9, '元素2']、  
  
// 合并嵌套数组 会浅拷贝嵌套数组  
let d = [1, 2];  
let e = [3, [4]];  
let newArr4 = d.concat(e);    // [1, 2, 3, [4]]

从中间位置插入

splice()

详见后面“增删改都能用”说明

 

从头部删除

shift()

定义: shift()方法删除数组的第一个元素,并返回这个元素。

示例

let arr = ['pink', 'aqua', 'blue'];  
arr.shift();    // 'pink'  
// arr: ['aqua', 'blue']

从尾部删除

pop()

定义: pop() 方法删除一个数组中的最后的一个元素,并且返回这个元素。

示例

let arr = ['pink', 'aqua', 'blue'];  
arr.pop();    // 'blue'  
// arr: ['pink', 'aqua']

从中间位置删除

splice()

详见后面“增删改都能用”说明

 

splice()

详见后面“增删改都能用”说明

 

增删改都能用

splice()

定义:splice()方法从数组添加/删除项目后,返回被删除的项目

语法: array.splice(index,howmany,item1,.....,itemX)

参数:

index: 必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾出规定位置。  
howmany:可选。要删除的项目数量。如果设置为0,则不会删除项目。  
item1,...,itemX: 可选,向数组添加新项目

返回值:如果有元素被删除,返回包含被删除项目的新数组。

示例

// Example 1  
// 在 index2的地方,删除0项数据,并插入"drum"  
let arr = ['angel', 'clown', 'mandarin', 'sturgeon'];  
let removedArr = arr.splice(2, 0, 'drum');  
// arr: ["angel", "clown", "drum", "mandarin", "sturgeon"]  
// removedArr: []  
  
// Example 2  
// 在 index2的地方,删除0项数据,并插入"drum", "guitar"  
let arr = ['angel', 'clown', 'mandarin', 'sturgeon'];  
let removedArr = arr.splice(2, 0, 'drum', 'guitar');  
// arr: ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]  
// removedArr: []  
  
// Example 3  
// 在 index3的地方,删除1项数据  
let arr = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];  
let removedArr = myFish.splice(3, 1);  
// arr: ["angel", "clown", "drum", "sturgeon"]  
// removedArr: ["mandarin"]  
  
// Example 4  
// 在 index2的地方,删除1项数据,并插入 "trumpet"  
let arr = ['angel', 'clown', 'drum', 'sturgeon'];  
let removedArr = arr.splice(2, 1, 'trumpet');  
// arr: ["angel", "clown", "trumpet", "sturgeon"]  
// removedArr: ["drum"]  
  
// Example 5  
// 在 index0的地方,删除2项数据,并插入 "parrot", "anemone", "blue"  
let arr = ['angel', 'clown', 'trumpet', 'sturgeon'];  
let removedArr = arr.splice(0, 2, 'parrot', 'anemone', 'blue');  
// arr: ["parrot", "anemone", "blue", "trumpet", "sturgeon"]  
// removedArr: ["angel", "clown"]

forEach

定义:为每个数组元素执行一次提供的函数。

语法: forEach(callbackFn)

示例

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

map

定义:创建一个新数组,其中包含调用数组中每个元素上调用提供函数的结果。

语法: map(callbackFn)

示例

const array1 = [1, 4, 9, 16];  
  
const map1 = array1.map((x) => x * 2);  
  
console.log(map1);  
// [2, 8, 18, 32]  
  
const kvArray = [  
    { key: 1, value: 10 },  
    { key: 2, value: 20 },  
    { key: 3, value: 30 }  
];  
const reformattedArray = kvArray.map(({ key, value }) => ({ [key]: value }));  
  
console.log(reformattedArray);  
// [{ 1: 10 }, { 2: 20 }, { 3: 30 }]  
console.log(kvArray);  
// [  
//   { key: 1, value: 10 },  
//   { key: 2, value: 20 },  
//   { key: 3, value: 30 }  
// ]

reduce/reduceRight

定义:按顺序(reduceRight是倒序)对数组的每个元素执行用户提供的“还原器”回调函数,传递前一个元素计算的返回值。在数组的所有元素上运行还原器的最终结果是单个值。

首次运行回调时,没有“上一个计算的返回值”。如果提供,可以代替其使用初始值。否则,索引0的数组元素用作初始值,迭代从下一个元素开始(索引1而不是索引0)。

语法: reduce(callbackFn) reduce(callbackFn, initialValue) reduceRight(callbackFn) reduceRight(callbackFn, initialValue)

示例

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);  
// 10  
  
const array2 = [  
  [0, 1],  
  [2, 3],  
  [4, 5]  
];  
  
const result = array2.reduceRight((accumulator, currentValue) =>  
  accumulator.concat(currentValue),  
);  
  
console.log(result);  
// [4,5,2,3,0,1]

every

定义:测试数组中的所有元素是否通过提供函数实现的测试。它返回一个布尔值。

语法: every(callbackFn)

示例

const isBelowThreshold = (currentValue) => currentValue < 40;  
const isBelowThreshold2 = (currentValue) => currentValue > 1;  
  
const array1 = [1, 30, 39, 29, 10, 13];  
  
console.log(array1.every(isBelowThreshold));  
  
const array1 = [1, 30, 39, 29, 10, 13];  
  
console.log(array1.every(isBelowThreshold));  
// true  
  
console.log(array1.every(isBelowThreshold2));  
// false

some

定义:测试数组中的至少一个元素是否通过了提供函数实现的测试。如果在数组中找到提供的函数返回true的元素,则返回true;否则返回false。它不会修改数组。

语法: some(callbackFn)

示例

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

filter

定义:创建给定数组的一部分的浅副本,仅过滤到给定数组中通过提供函数实现的测试的元素。

语法: filter(callbackFn)

示例

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

find

定义:返回提供数组中满足提供测试函数的第一个元素。如果没有满足测试函数的值,则返回 undefined。

语法: find(callbackFn)

示例

const array1 = [  
  {id:1},  
  {id:10},  
  {id:12},  
  {id:19},  
  {id:100}  
];  
  
const found = array1.find((element) => element.id > 10);  
  
console.log(found);  
// {id:12}

findIndex

定义:返回满足提供的测试函数的数组中第一个元素的索引。如果没有元素满足测试函数,则返回-1。

语法: findIndex(callbackFn)

示例

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

includes

定义:确定数组是否在其条目中包含某个值,并返回true或false。

语法: includes(searchElement) includes(searchElement, fromIndex)

示例

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

console.log(pets.includes('at'));  
// false

at

定义:获取一个整数值,并在该索引处返回项目,允许正整数和负整数。负整数从数组中的最后一个项目开始计数。

语法: at(index)

描述:

当index是非负整数时,at()方法等同于括号符号。例如,array[0]和array.at(0)都返回第一个项目。然而,在计算数组末尾的元素时,就不能像这样array[-1]使用,因为方括号内的所有值都被视为字符串属性,因此您最终将读取array["-1"],这只是一个正常的字符串属性,而不是数组索引。

示例

const array1 = [5, 12, 8, 130, 44];  
  
let index = 2;  
  
console.log(`An index of ${index} returns ${array1.at(index)}`);  
// "An index of 2 returns 8"  
  
index = -2;  
  
console.log(`An index of ${index} returns ${array1.at(index)}`);  
// "An index of -2 returns 130"

indexOf

定义:返回在数组中可以找到给定元素的第一个索引,如果没有,则返回-1。

语法: indexOf(searchElement) indexOf(searchElement, fromIndex)

示例

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

其他

flat

定义:创建了一个新数组,所有子数组元素递归地串入到指定深度。

语法: flat() flat(depth)

示例

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]

join

定义:通过串联此数组中的所有元素来创建并返回一个新字符串,并用逗号或指定的分隔符字符串隔开。如果数组只有一个项目,那么该项目将在不使用分隔符的情况下返回。

语法: join() join(separator)

示例

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

reverse/toReversed

定义:方法将数组反转,并返回对同一数组的引用,第一个数组元素现在成为最后一个,最后一个数组元素成为第一个。换句话说,数组中的元素顺序将转向与之前所述相反的方向。

要在不改变原始数组的情况下反转数组中的元素,请使用toReversed()

语法: reverse() toReversed()

示例

const array1 = ['one', 'two', 'three'];  
console.log('array1:', array1);  
// "array1:" ["one", "two", "three"]  
  
const reversed = array1.reverse();  
console.log('reversed:', reversed);  
// "reversed:" ["three", "two", "one"]  
  
console.log('array1:', array1);  
// "array1:" ["three", "two", "one"]  
  
const items = [1, 2, 3];  
console.log(items); // [1, 2, 3]  
const reversedItems = items.toReversed();  
console.log(reversedItems); // [3, 2, 1]  
console.log(items); // [1, 2, 3]

sort/toSorted

定义:对数组的元素进行排序,并返回对同一数组的引用,然后排序。默认排序顺序是升序,建立在将元素转换为字符串的基础上,然后比较其UTF-16代码单元值的序列。

要在不改变原始数组的情况下对数组中的元素进行排序,请使用toSorted()

语法: sort() sort(compareFn) toSorted() toSorted(compareFn)

示例

const numberArray = [40, 1, 5, 200];  
function compareNumbers(a, b) {  
  return a - b;  
}  
numberArray.sort(); // [1, 200, 40, 5]  
numberArray.sort(compareNumbers); // [1, 5, 40, 200]  
  
const numericStringArray = ["80", "9", "700"];  
numericStringArray.sort(); // ['700', '80', '9']  
numericStringArray.sort(compareNumbers); // ['9', '80', '700']  
  
const mixedNumericArray = ["80", "9", "700", 40, 1, 5, 200];  
mixedNumericArray.sort(); // [1, 200, 40, 5, '700', '80', '9']  
mixedNumericArray.sort(compareNumbers); // [1, 5, '9', 40, '80', 200, '700']  
  
  
const months = ["Mar", "Jan", "Feb", "Dec"];

const sortedMonths = months.toSorted();  
console.log(sortedMonths); // ['Dec', 'Feb', 'Jan', 'Mar']  
console.log(months); // ['Mar', 'Jan', 'Feb', 'Dec']
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]  
  
  
const items = [    { name: "Edward", value: 21 },    { name: "Sharpe", value: 37 },  { name: "And", value: 45 },    { name: "The", value: -12 },    { name: "Magnetic", value: 13 },    { name: "Zeros", value: 37 },  ];  
// sort by value  
items.sort((a, b) => a.value - b.value);  
console.log(items);  
// sort by name  
items.sort((a, b) => {  
  const nameA = a.name.toUpperCase(); // ignore upper and lowercase  
  const nameB = b.name.toUpperCase(); // ignore upper and lowercase  
  if (nameA < nameB) {  
    return -1;
    }  
  if (nameA > nameB) {  
    return 1;  
  }  
  
  // names must be equal  
  return 0;  
});  
console.log(items);

slice

定义:将数组的一部分的浅副本返回到从start到end选择的新数组对象(不包括end),其中start和end代表该数组中项目的索引。原始数组将不会被修改。

语法: slice() slice(start) slice(start, end)

示例

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));  
// ["bison", "camel", "duck", "elephant"]  
  
console.log(animals.slice(-2));  
// ["duck", "elephant"]  
  
console.log(animals.slice(2, -1));  
// ["camel", "duck"]  
  
console.log(animals.slice());  
// ["ant", "bison", "camel", "duck", "elephant"]