Seven New JavaScript Array Methods Introduced in the Last Three Years
This article introduces seven brand‑new JavaScript array methods released in the past three years, explains their usage with clear examples, demonstrates how they differ from traditional approaches, and provides browser compatibility tables for each method.
本文分享 7 个近三年出现的全新 JavaScript 数组方法,很实用!
Array.prototype.at()
at() 方法允许通过索引访问数组中的元素,支持负数索引来从数组末尾开始计数。
const arr = [10, 20, 30, 40];
console.log(arr.at(2)); // 输出: 30
console.log(arr.at(-1)); // 输出: 40通常情况下,我们会使用 [index] 索引来获取数组元素,但这种方式获取正数元素还可以,如果想要获取倒数元素,就麻烦一点,这时就可以借助 at() 方法来实现,只需指定一个负数即可。
浏览器支持情况:
Array.prototype.with()
with() 方法返回一个新数组,该数组是原数组的一个副本,但指定索引处的元素被替换为新的值。
const arr = [1, 2, 3, 4, 5];
const newArr = arr.with(2, 99); // 将索引2处的元素替换为99
console.log(newArr); // 输出: [1, 2, 99, 4, 5]
console.log(arr); // 输出: [1, 2, 3, 4, 5] (原数组不变)当需要更新数组中特定位置的元素但不想修改原数组时,可以使用 with() 方法。
浏览器支持情况:
Array.prototype.toSorted()
toSorted() 方法返回一个新数组,该数组是原数组经过排序后的副本,不会修改原数组,它是 sort() 方法的复制版本。
const arr = [1, 5, 3, 2, 4];
const sortedArr = arr.toSorted((a, b) => a - b);
console.log(sortedArr); // 输出: [1, 2, 3, 4, 5]
console.log(arr); // 输出: [1, 5, 3, 2, 4] (原数组不变)当需要对数组进行排序但不想修改原数组时,可以使用 toSorted() 方法。
浏览器支持情况:
Array.prototype.toReversed()
toReversed() 方法返回一个新数组,该数组是原数组反转后的副本,不会修改原数组,它是 reverse() 方法对应的复制版本。
const arr = [1, 2, 3, 4, 5];
const reversedArr = arr.toReversed();
console.log(reversedArr); // 输出: [5, 4, 3, 2, 1]
console.log(arr); // 输出: [1, 2, 3, 4, 5] (原数组不变)当需要反转数组但不想修改原数组时,可以使用 toReversed() 方法。
浏览器支持情况:
Array.prototype.toSpliced()
toSpliced() 方法返回一个新数组,该数组是从原数组中删除或替换某些元素后的新数组,不会修改原数组,它是 splice() 方法的复制版本。
const arr = [1, 2, 3, 4, 5];
const splicedArr = arr.toSpliced(2, 1, 99); // 从索引2开始删除1个元素并插入99
console.log(splicedArr); // 输出: [1, 2, 99, 4, 5]
console.log(arr); // 输出: [1, 2, 3, 4, 5] (原数组不变)当需要从数组中删除或替换某些元素但不想修改原数组时,可以使用 toSpliced() 方法。
浏览器支持情况:
Array.prototype.findLast()
findLast() 方法返回数组中满足提供的测试函数的最后一个元素,类似 find() 的反向操作。如果没有找到,则返回 undefined 。
const arr = [5, 12, 8, 130, 44];
const found = arr.findLast(element => element > 10);
console.log(found); // 输出: 44当需要在数组中查找符合条件的最后一个元素时,可以使用 findLast() 方法。
浏览器支持情况:
Array.prototype.findLastIndex()
findLastIndex() 方法返回数组中满足提供的测试函数的最后一个元素的索引。如果没有找到,则返回 -1 。
const arr = [5, 12, 8, 130, 44];
const index = arr.findLastIndex(element => element > 10);
console.log(index); // 输出: 4 (因为44是最后一个大于10的元素)当需要在数组中查找符合条件的最后一个元素的索引时,可以使用 findLastIndex() 方法。
浏览器支持情况:
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.