Array.prototype.with()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2023年7月.
Array 实例的 with() 方法是使用方括号表示法修改指定索引值的复制方法版本。它会返回一个新数组,其指定索引处的值会被新值替换。
语法
arrayInstance.with(index, value)
参数
index-
要修改的数组索引(从 0 开始),将会转换为整数。
- 负数索引会从数组末尾开始计数——即当
index < 0时,会使用index + array.length。 - 如果规范化后的索引超出数组边界,会抛出
RangeError。
- 负数索引会从数组末尾开始计数——即当
value-
要分配给指定索引的任何值。
返回值
一个全新的数组,其中 index 索引处的元素被替换为 value。
异常
RangeError-
index > array.length或index < -array.length时抛出。
描述
with() 通过返回一个指定索引处的值被新值替换的新数组,来改变数组中指定索引处的值。原数组不会被修改,这使得你可以以链式调用数组方法的方式来对数组进行操作。
通过组合使用with() 和 at() 函数,可分别地写入和读取数组,索引使用正数负数均可。
with() 方法永远不会产生稀疏数组。如果原数组是稀疏的,新数组对应的空白索引位置会替换为 undefined。
with() 方法是通用的。它只期望 this 值具有 length 属性和整数键属性。
示例
>创建一个新的数组,改变其中一个元素
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() 方法,你可以在更新一个数组元素后继续调用其他的数组方法。
const arr = [1, 2, 3, 4, 5];
console.log(arr.with(2, 6).map((x) => x ** 2)); // [1, 4, 36, 16, 25]
在稀疏数组上使用 with()
with() 方法总会创建一个密集数组。
const arr = [1, , 3, 4, , 6];
console.log(arr.with(0, 2)); // [2, undefined, 3, 4, undefined, 6]
在非数组对象上调用 with()
with() 方法创建并返回一个新数组。它读取 this 的 length 属性,然后访问其键是小于 length 的非负整数的每个属性。当 this 的每个属性被访问后,索引等于该属性的键的数组元素被设置为该属性的值。最后,将 index 的数组值设置为 value。
const arrayLike = {
length: 3,
unrelated: "foo",
0: 5,
2: 4,
3: 3, // 由于 length 属性的值为 3,with() 会忽略该值
};
console.log(Array.prototype.with.call(arrayLike, 0, 1));
// [ 1, undefined, 4 ]
规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-array.prototype.with> |