Array.prototype.with()

Baseline 2023
新推出

自 2023 年 7 月以来,此功能可在最新的设备和浏览器版本上运行。此功能可能不适用于旧设备或浏览器。

Array 实例的 with() 方法是使用 方括号表示法修改给定索引值的 复制版本。它返回一个新数组,其中给定索引处的元素被替换为给定的值。

语法

js
arrayInstance.with(index, value)

参数

index

要更改数组的零基索引,将该索引转换为整数

  • 负数索引从数组末尾开始计数——如果 -array.length <= index < 0,则使用 index + array.length
  • 如果规范化后的索引超出范围,将抛出 RangeError
value

要赋给给定索引的任何值。

返回值

一个新数组,其中 index 处的元素被 value 替换。

异常

RangeError

如果 index >= array.lengthindex < -array.length,则抛出此错误。

描述

with() 方法会更改数组中给定索引的值,并返回一个新数组,其中给定索引处的元素被替换为给定的值。原始数组不会被修改。这允许您在进行操作的同时链式调用数组方法。

通过将 with()at() 结合使用,您可以使用负数索引来读取(分别)和写入数组。

with() 方法从不生成 稀疏数组。如果源数组是稀疏的,则在新数组中,空位将被 undefined 替换。

with() 方法是 通用的。它只期望 this 值具有 length 属性和整数键属性。

示例

创建一个修改了单个元素的新数组

js
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]

链式调用数组方法

使用 with() 方法,您可以更新数组中的单个元素,然后应用其他数组方法。

js
const arr = [1, 2, 3, 4, 5];
console.log(arr.with(2, 6).map((x) => x ** 2)); // [1, 4, 36, 16, 25]

在稀疏数组上使用 with()

with() 方法始终创建一个密集数组。

js
const arr = [1, , 3, 4, , 6];
console.log(arr.with(0, 2)); // [2, undefined, 3, 4, undefined, 6]

在非数组对象上调用 with()

with() 方法会创建并返回一个新数组。它读取 thislength 属性,然后访问键小于 length 的所有非负整数键属性。当访问 this 的每个属性时,索引等于该属性键的数组元素将被设置为该属性的值。最后,数组在 index 处的值被设置为 value

js
const arrayLike = {
  length: 3,
  unrelated: "foo",
  0: 5,
  2: 4,
  3: 3, // ignored by with() since length is 3
};
console.log(Array.prototype.with.call(arrayLike, 0, 1));
// [ 1, undefined, 4 ]

规范

规范
ECMAScript® 2026 语言规范
# sec-array.prototype.with

浏览器兼容性

另见