JS Array数组的常用方法

数组的常用方法汇总

  1. at()
  • 作用:获取指定索引对应的元素
  • 语法:at(index) index元素的索引
  • 返回值:指定索引匹配的元素
const array = ['a', 'b', 'c', 'd', 'e', 'f']
console.log(array.at(3)) // d
  1. concat()
  • 作用:合并两个或多个数组,不改变原有数组
  • 语法:concat(value0, value1, /* … ,*/ valueN) valueN可选,或不传则返回该数组的浅拷贝
  • 返回值:新数组
const array1 = ['a', 'b', 'c']
const array2 = ['d', 'e', 'f']
console.log(array1.concat(array2)) // ["a", "b", "c", "d", "e", "f"]
  1. copyWithin()
  • 作用:复制数组的一部分到同一数组中的另一个位置
  • 语法:copyWithin(target, start, end) target目标位置,start/end可选,起始位置/结束位置
  • 返回值:复制后的数组,原数组长度不变
const array = ['a', 'b', 'c', 'd', 'e', 'f']
const copy1 = array.copyWithin(0,3,5)
console.log(array, copy1) // Array ["d", "e", "c", "d", "e", "f"] Array ["d", "e", "c", "d", "e", "f"]
  1. entries()
  • 作用:获取数组迭代器对象,这个对象包含每个索引的键/值对
  • 语法: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"]
  1. every()
  • 作用:验证数组内每一项是否都符合指定函数的测试
  • 语法:every(callbackFn) callbackFn每个元素执行的函数,参数有element当前处理的元素,index当前处理的索引,array调用every的数组本身,返回布尔值
  • 返回值:true/false, 如果callbackFn为每一项元素返回真值,则为true,否则为false。
const isBelowThreshold = (currentValue) => currentValue < 40;

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

console.log(array1.every(isBelowThreshold));
// Expected output: true
  1. fill()
  • 作用:用固定值填充数组,可指定起始索引和终止索引
  • 语法:fill(value, start, end) value为要填充的元素。start可选,从数组哪个索引开始填充。end可选,结束索引,不包含end索引
  • 返回值:填充后的数组
const array1 = [1, 2, 3, 4];
console.log(array1.fill(0, 2, 4)); // [1, 2, 0, 0]
console.log(array1.fill(5, 1)); // [1, 5, 5, 5]
console.log(array1.fill(6)); // [6, 6, 6, 6]
  1. filter()
  • 作用:获取数组满足过滤函数的一部分元素
  • 语法:filter(callbackFn, thisArg) callbackFn为每个元素执行的函数,其参数有element(当前正在处理的元素), index(正在处理的元素在数组中的索引), array(调用filter数组本身),应该返回布尔值。 thisArg可选,执行 callbackFn 时用作 this 的值。
  • 返回值:
const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter((word) => word.length > 6); // 过滤字符长度大于6的元素
console.log(result); // ["exuberant", "destruction", "present"]
  1. find()
  • 作用:获取数组中满足函数的第一个元素的值。
    • 如果需要在数组中找到对应元素的索引,请使用 findIndex()。
    • 如果需要查找某个值的索引,请使用 Array.prototype.indexOf()。(它类似于 findIndex(),但只是检查每个元素是否与值相等,而不是使用测试函数。)
    • 如果需要查找数组中是否存在某个值,请使用 Array.prototype.includes()。同样,它检查每个元素是否与值相等,而不是使用测试函数。
    • 如果需要查找是否有元素满足所提供的测试函数,请使用 Array.prototype.some()。
  • 语法:find(callbackFn, thisArg) callbackFn为每个元素执行的函数,其参数有element(当前正在处理的元素), index(正在处理的元素在数组中的索引), array(调用filter数组本身),应该返回布尔值。thisArg可选,执行 callbackFn 时用作 this 的值。
  • 返回值:满足函数的第一个元素的值。否则返回 undefined。
const array1 = [5, 12, 8, 130, 44];
const found = array1.find((element) => element > 10);
console.log(found); // 12
  1. findIndex()
  • 作用:获取数组中函数的第一个元素的索引。若没有找到对应元素则返回 -1。
  • 语法:findIndex(callbackFn, thisArg) callbackFn为每个元素执行的函数,其参数有element(当前正在处理的元素), index(正在处理的元素在数组中的索引), array(调用filter数组本身),应该返回布尔值。thisArg可选,执行 callbackFn 时用作 this 的值。
  • 返回值:满足函数的第一个元素的索引。否则返回 -1。
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber)); // 3
  1. findLast()
  • 作用:反向迭代数组,并返回满足提供的测试函数的第一个元素的值。
  • 语法: findLast(callbackFn, thisArg) callbackFn为每个元素执行的函数,其参数有element(当前正在处理的元素), index(正在处理的元素在数组中的索引), array(调用filter数组本身),应该返回布尔值。thisArg可选,执行 callbackFn 时用作 this 的值。
  • 返回值:满足函数的第一个元素的值。否则返回 undefined。
const array1 = [5, 12, 50, 130, 44];
const found = array1.findLast((element) => element > 45);
console.log(found); // 130
  1. findLastIndex()
  • 作用:反向迭代数组,获取数组中函数的第一个元素的索引。若没有找到对应元素则返回 -1。
  • 语法:findLastIndex(callbackFn, thisArg) callbackFn为每个元素执行的函数,其参数有element(当前正在处理的元素), index(正在处理的元素在数组中的索引), array(调用filter数组本身),应该返回布尔值。thisArg可选,执行 callbackFn 时用作 this 的值。
  • 返回值:满足函数的第一个元素的索引。否则返回 -1。
const array1 = [5, 12, 50, 130, 44];
const isLargeNumber = (element) => element > 45;
console.log(array1.findIndex(isLargeNumber)); // 3
  1. 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]
  1. flatMap()
  • 作用:过滤数组每个元素,将返回的数组展开一级进行拼接,返回新数组。相当于调用map后再深度深度为1的flat方法。
  • 语法:flatMap(callbackFn, thisArg) callbackFn为每个元素执行的函数,其参数有element(当前正在处理的元素), index(正在处理的元素在数组中的索引), array(调用filter数组本身),应该返回一个数组或者要添加到新数组中的单个非数组值。thisArg可选,执行 callbackFn 时用作 this 的值。
  • 返回值:新数组
const arr1 = [1, 2, 1, 3];
const result = arr1.flatMap((num) => (num === 2 ? [2, 2] : 1));
console.log(result);
// Expected output: Array [1, 2, 2, 1, 1]
  1. forEach()
  • 作用: 遍历数组每个元素,执行给定的函数
    • forEach除非抛出异常,否则无法停止循环,若有这样的需求应该使用for、 for…of、for…in来实现提前终止。
  • 语法:forEach(callbackFn, thisArg) callbackFn为数组中每个元素执行的函数,其参数有element(当前正在处理的元素), index(正在处理的元素在数组中的索引), array(调用filter数组本身),无返回值。callbackFn期望是同步函数,若使用Promise或异步函数可能不是你期望的结果。thisArg可选,执行 callbackFn 时用作 this 的值。
  • 返回值:无返回值(undefined)
const array1 = ['a', 'b', 'c'];
array1.forEach((element) => console.log(element)); // 依次输出 'a' 'b' 'c'
  1. from()
  • 作用:从可迭代或类数组对象创建一个新的浅拷贝的数组
  • 语法:Array.from(arrayLike, mapFn(element, index), thisArg) arrayLike要转换成数组的类数组或可迭代对象。mapFn可选,每个将要添加到数组中的值首先会传递给该函数,然后将 mapFn 的返回值增加到数组中。thisArg可选,执行 mapFn 时用作 this 的值。
  • 返回值:新数组
console.log(Array.from('foo'));
// Expected output: Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], (x) => x + x));
// Expected output: Array [2, 4, 6]
  1. fromAsync()
  • 作用:转换异步的可迭代对象到数组
  • 语法:Array.fromAsync(arrayLike, mapFn, thisArg) arrayLike要转换成数组的类数组或可迭代对象。mapFn可选,每个将要添加到数组中的值首先会传递给该函数,然后将 mapFn 的返回值增加到数组中。thisArg可选,执行 mapFn 时用作 this 的值。
  • 返回值:一个新的 Promise,其兑现值是一个新的 Array 实例。
const asyncIterable = (async function* () {
  for (let i = 0; i < 5; i++) {
    await new Promise((resolve) => setTimeout(resolve, 10 * i));
    yield i;
  }
})();

Array.fromAsync(asyncIterable).then((array) => console.log(array)); // Array [0, 1, 2, 3, 4]
  1. includes()
  • 作用:判断一个数组是否包含一个指定的值
  • 语法:includes(searchElement, fromIndex) searchElement需要查找的值。fromIndex可选,开始搜索的索引(从零开始),会转换为整数
  • 返回值:如果包含则返回 true,否则返回 false。
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
  1. indexOf()
  • 作用:获取数组中第一次指定元素的下标
  • 语法:indexOf(searchElement, fromIndex) searchElement需要查找的值。fromIndex可选,开始搜索的索引(从零开始),会转换为整数
  • 返回值:首个被找到的元素在数组中的索引位置; 若没有找到则返回 -1。
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// Expected output: 1
console.log(beasts.indexOf('bison', 2));
// Expected output: 4
console.log(beasts.indexOf('giraffe'));
// Expected output: -1
  1. isArray()
  • 作用:确定传递的值是否是一个数组。
  • 语法:Array.isArray(value) value为需要检测的值。
  • 返回值:如果 value 是 Array,则为 true;否则为 false。
console.log(Array.isArray([1, 3, 5]));
// Expected output: true
console.log(Array.isArray('[]'));
// Expected output: false
console.log(Array.isArray(new Array(5)));
// Expected output: true
console.log(Array.isArray(new Int16Array([15, 33])));
// Expected output: false
  1. join()
  • 作用:将一个数组(或一个类数组对象)的所有元素用逗号或指定的分隔符连接成一个字符串并返回。
  • 语法:join(separator) 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"
  1. keys()
  • 作用:数组迭代器对象,其中包含数组中每个索引的键。
  • 语法: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
  1. lastIndexOf()
  • 作用:数组中指定元素最后一次出现的索引。
  • 语法:lastIndexOf(searchElement, fromIndex) searchElement要查找的元素。fromIndex可选,以 0 起始的索引,表明反向搜索的起始位置。
  • 返回值:指定元素最后一次出现的索引,如果不存在则返回 -1。
const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

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

console.log(animals.lastIndexOf('Tiger'));
// Expected output: 1
  1. map()
  • 作用:遍历数组,用指定函数创建一个新数组。
  • 语法:map(callbackFn, thisArg) callbackFn为数组中的每个元素执行的函数。它的返回值作为一个元素被添加为新数组中。参数有element(当前正在处理的元素), index(当前正在处理元素的索引),array(调用map的数组本身)。thisArg可选,执行 callbackFn 时用作 this 的值。
  • 返回值:指定元素最后一次出现的索引,如果不存在则返回 -1。
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]
  1. of()
  • 作用:通过可变数量的参数创建一个新的数组。
  • 语法:Array.of(element0, element1, …, elementN)。 elementN用于创建数组的元素
  • 返回值:数组。
console.log(Array.of('foo', 2, 'bar', true));
// Expected output: Array ["foo", 2, "bar", true]

console.log(Array.of());
// Expected output: Array []
  1. pop()
  • 作用:数组中删除最后一个元素。原数组改变
  • 语法:Array.of(element0, element1, …, elementN)。 elementN用于创建数组的元素
  • 返回值:删除的元素的值。
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// Expected output: "tomato"
console.log(plants);
// Expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
plants.pop();
console.log(plants);
// Expected output: Array ["broccoli", "cauliflower", "cabbage"]
  1. push()
  • 作用:向数组末尾添加指定元素,原数组改变。
  • 语法:push(element0, element1, … , elementN) elementN为要添加的元素
  • 返回值:调用方法的对象的新 length 属性。
const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('cows');
console.log(count);
// Expected output: 4
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
  1. reduce()
  • 作用:为数组中的每一个元素依次执行回调函数,每一次运行函数会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。
  • 语法:reduce(callbackFn, initialValue)
    • callbackFn(accumulator, currentValue, currentIndex, array)
      accumulator为上一次调用callbackFn的结果,
      currentValue为当前元素,
      currentIndex当前元素在数组中的索引,
      array为调用reduce的数组本身。
      callbackFn返回值将作为下一次调用 callbackFn 时的 accumulator 参数。
    • initialValue可选,为第一次执行回调时初始值,如果指定了initialValue,则callbackFn从数组第一个值作为currentValue,否则数组第一个值作为accumulator,从数组第二值作为currentValue。
  • 返回值:聚合后的结果值
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
  1. reduceRight()
  • 作用:从右向左为数组中的每一个元素依次执行回调函数,每一次运行函数会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。
  • 语法:reduceRight(callbackFn, initialValue)
    • callbackFn(accumulator, currentValue, currentIndex, array)
      accumulator为上一次调用callbackFn的结果,
      currentValue为当前元素,
      currentIndex当前元素在数组中的索引,
      array为调用reduce的数组本身。
      callbackFn返回值将作为下一次调用 callbackFn 时的 accumulator 参数。
    • initialValue可选,为第一次执行回调时初始值,如果指定了initialValue,则callbackFn从数组第一个值作为currentValue,否则数组第一个值作为accumulator,从数组第二值作为currentValue。
  • 返回值:聚合后的结果值
const array1 = [
  [0, 1],
  [2, 3],
  [4, 5],
];

const result = array1.reduceRight((accumulator, currentValue) =>
  accumulator.concat(currentValue),
);

console.log(result);
// Expected output: Array [4, 5, 2, 3, 0, 1]
  1. reverse()
  • 作用:反转数组,会改变原数组,若不改变原数组使用roReversed()
  • 语法:reverse()
  • 返回值:原数组反转后的数组
const reversed = array1.reverse();
console.log('reversed:', reversed);
// Expected output: "reversed:" Array ["three", "two", "one"]
console.log('array1:', array1);
// Expected output: "array1:" Array ["three", "two", "one"]
  1. shift()
  • 作用:删除数组第一个元素,会改变原数组
  • 语法:shift()
  • 返回值:删除的元素
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
// Expected output: Array [2, 3]
console.log(firstElement);
// Expected output: 1
  1. slice()
  • 作用:复制数组或数组的一部分,不改变原数组
  • 语法:slice(start, end)
    start可选,提取起始索引。
    • 如果索引是负数,则从数组末尾开始计算——如果 start < 0,则使用 start + array.length。
    • 如果 start < -array.length 或者省略了 start,则使用 0。
    • 如果 start >= array.length,则不提取任何元素。
      end可选,提取终止索引,不包括 end 的位置。
    • 如果索引是负数,则从数组末尾开始计算——如果 end < 0,则使用 end + array.length。
    • 如果 end < -array.length,则使用 0。
    • 如果 end >= array.length 或者省略了 end,则使用 array.length,提取所有元素直到末尾。
    • 如果 end 在规范化后小于或等于 start,则不提取任何元素。
  • 返回值:新数组
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());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]
  1. some()
  • 作用:检测数组中是否至少有一项符合要求的元素
  • 语法:some(callbackFn, thisArg)
    • callbackFn为数组中的每个元素执行的函数,应该返回一个布尔值,调用时将传入element、index、array。
    • element为当前正在处理的元素
    • index为当前处理元素的索引
    • array为调用some()的数组本身
    • thisArg可选,执行callbanckFn时用作this数组
  • 返回值:如果回调函数对数组中至少一个元素返回一个真值,则返回 true。否则返回 false。
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
  1. sort()
  • 作用:对数组进行排序,会改变原数组,如不想改变原数组使用toSorted()
  • 语法:sort(compareFn)
    • compareFn可选,为定义排序的函数,返回值应为一个数字。其符号表示两个元素的相对顺序:如果 a 小于 b,返回值为负数,如果 a 大于 b,返回值为正数,如果两个元素相等,返回值为 0。NaN 被视为 0。
    • 该函数使用以下参数调用:
    • a 第一个用于比较的元素。
    • b 第二个用于比较的元素。
    • 如果省略该函数,数组元素会被转换为字符串,然后根据每个字符的 Unicode 码位值进行排序。
  • 返回值:排序后的原数组
function compareNumbers(a, b) {
  return a - b;
}

const numberArray = [40, 1, 5, 200];
numberArray.sort(); // [1, 200, 40, 5]
numberArray.sort(compareNumbers); // [1, 5, 40, 200]

// 对象数组可以通过比较它们的某个属性的值来排序。
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 },
];

// 根据 value 排序
items.sort((a, b) => a.value - b.value);
console.log(items)
// > Array [Object { name: "The", value: -12 }, Object { name: "Magnetic", value: 13 }, Object { name: "Edward", value: 21 }, Object { name: "Sharpe", value: 37 }, Object { name: "Zeros", value: 37 }, Object { name: "And", value: 45 }]
  1. splice()
  • 作用:移除或者替换已存在的元素,或添加新的元素,会改变原数组,若不改变原数组使用toSpliced()

  • 语法:splice(start)
    splice(start, deleteCount)
    splice(start, deleteCount, item1)
    splice(start, deleteCount, item1, item2)
    splice(start, deleteCount, item1, item2, /* …, */ itemN)

    • start 要开始改变数组的位置
    • deleteCount 可选,要删除元素的数量,若省略deleteCount,或者其值大于或等于由 start 指定的位置到数组末尾的元素数量,那么从 start 到数组末尾的所有元素将被删除。
    • item1、…、itemN 可选从 start 开始要加入到数组中的元素。如果不指定任何元素,splice() 将只从数组中删除元素。
  • 返回值:一个包含了删除的元素的数组。如果只移除一个元素,则返回一个元素的数组。如果没有删除任何元素,则返回一个空数组。

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"]
  1. toLocaleString()
  • 作用:将数组每一项调用自身的toLocaleString方法转换为字符串并用逗号拼接
  • 语法:toLocaleString(locales, options)
  • locales可选,带有 BCP 47 语言标签的字符串,或者此类字符串的数组
  • options可选,配置属性的对象
  • 返回值:字符串
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",
  1. toReversed()
  • 作用:反转数组,但不改变原数组
  • 语法:toReversed()
  • 返回值:相反顺序排列元素的新数组()
const items = [1, 2, 3];
const reversedItems = items.toReversed();
console.log(reversedItems); // [3, 2, 1]
console.log(items); // [1, 2, 3]
  1. toSorted()
  • 作用:对数组进行排序,但不改变原数组
  • 语法:toSorted(compareFn)
    • compareFn可选,为定义排序的函数,返回值应为一个数字。其符号表示两个元素的相对顺序:如果 a 小于 b,返回值为负数,如果 a 大于 b,返回值为正数,如果两个元素相等,返回值为 0。NaN 被视为 0。
    • 该函数使用以下参数调用:
    • a 第一个用于比较的元素。
    • b 第二个用于比较的元素。
    • 如果省略该函数,数组元素会被转换为字符串,然后根据每个字符的 Unicode 码位值进行排序。
  • 返回值:排序后的原数组
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]
  1. toSpliced()
  • 作用:是 splice() 方法的复制版本。它返回一个新数组,并在给定的索引处删除或替换了一些元素。

  • 语法:toSpliced(start)
    toSpliced(start, deleteCount)
    toSpliced(start, deleteCount, item1)
    toSpliced(start, deleteCount, item1, item2, itemN)

    • start 要开始改变数组的位置
    • deleteCount 可选,要删除元素的数量,若省略deleteCount,或者其值大于或等于由 start 指定的位置到数组末尾的元素数量,那么从 start 到数组末尾的所有元素将被删除。
    • item1、…、itemN 可选从 start 开始要加入到数组中的元素。如果不指定任何元素,splice() 将只从数组中删除元素。
  • 返回值:一个包含了删除的元素的数组。如果只移除一个元素,则返回一个元素的数组。如果没有删除任何元素,则返回一个空数组。

const months = ["Jan", "Mar", "Apr", "May"];

// 在索引 1 处添加一个元素
const months2 = months.toSpliced(1, 0, "Feb");
console.log(months2); // ["Jan", "Feb", "Mar", "Apr", "May"]

// 从第 2 个索引开始删除两个元素
const months3 = months2.toSpliced(2, 2);
console.log(months3); // ["Jan", "Feb", "May"]

// 在索引 1 处用两个新元素替换一个元素
const months4 = months3.toSpliced(1, 1, "Feb", "Mar");
console.log(months4); // ["Jan", "Feb", "Mar", "May"]

// 原数组不会被修改
console.log(months); // ["Jan", "Mar", "Apr", "May"]
  1. toString()
  • 作用:将数组转为字符串
  • 语法:toString()
  • 返回值:包含数组每个元素的字符串
const array1 = [1, 2, 'a', '1a'];

console.log(array1.toString());
// Expected output: "1,2,a,1a"
  1. unshift()
  • 作用:将指定元素添加到数组的开头,并返回数组的新长度
  • 语法:unshift(element1, element2, /* …, */ elementN) elementN为添加到 arr 开头的元素
  • 返回值:数组长度
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));
// Expected output: 5
console.log(array1);
// Expected output: Array [4, 5, 1, 2, 3]
  1. values()
  • 作用:获取数组的迭代器对象
  • 语法: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"
  1. with()
  • 作用:Array 实例的 with() 方法是使用方括号表示法修改指定索引值的复制方法版本
  • 语法:arrayInstance.with(index, value)
    • index为要修改的数组索引
    • value为要分配给指定索引的值
  • 返回值:index位置被替换为value后的新数组
const arr = [1, 2, 3, 4, 5];
console.log(arr.with(2, 6)); // [1, 2, 6, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值