Array.prototype.with()
语法
js
array.with(index, value)
参数
index
-
要修改的数组索引(从 0 开始),将会转换为整数。
- 负数索引会从数组末尾开始计数——即当
index < 0
时,会使用index + array.length
。 - 如果规范化后的索引超出数组边界,会抛出
RangeError
。
- 负数索引会从数组末尾开始计数——即当
value
-
要分配给指定索引的任何值。
返回值
一个全新的数组,其中 index
索引处的元素被替换为 value
。
异常
RangeError
-
index > array.length
或index < -array.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()
方法会读取 this
上的 length
属性,之后读取 this
上的每个整数键并写入到新数组中,同时 value
会被写入指定的 index
。
js
const arrayLike = {
length: 3,
unrelated: "foo",
0: 5,
2: 4,
};
console.log(Array.prototype.with.call(arrayLike, 0, 1));
// [ 1, undefined, 4 ]
规范
Specification |
---|
ECMAScript Language Specification # sec-array.prototype.with |
浏览器兼容性
BCD tables only load in the browser