Array.prototype.with()
Baseline 2023
Newly available
Since July 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
Array
实例的 with()
方法是使用 括号表示法 更改给定索引的值的 copying 版本。它返回一个新数组,其中给定索引处的元素替换为给定值。
¥The with()
method of Array
instances is the copying version of using the bracket notation to change the value of a given index. It returns a new array with the element at the given index replaced with the given value.
语法
参数
¥Parameters
index
-
要更改数组的从零开始的索引,转换为整数。
- 负索引从数组末尾开始倒数 — 如果使用
-array.length <= index < 0
、index + array.length
。 - 如果标准化后的索引越界,则抛出
RangeError
。
- 负索引从数组末尾开始倒数 — 如果使用
value
-
要分配给给定索引的任何值。
返回值
例外情况
描述
¥Description
with()
方法更改数组中给定索引的值,返回一个新数组,其中给定索引处的元素替换为给定值。原始数组没有被修改。这允许你在进行操作时链接数组方法。
¥The with()
method changes the value of a given index in the array, returning a new array with the element at the given index replaced with the given value. The original array is not modified. This allows you to chain array methods while doing manipulations.
通过将 with()
与 at()
组合,你可以使用负索引(分别)写入和读取数组。
¥By combining with()
with at()
, you can both write and read (respectively) an array using negative indices.
with()
方法永远不会产生 稀疏数组。如果源数组稀疏,则空槽将替换为新数组中的 undefined
。
¥The with()
method never produces a sparse array. If the source array is sparse, the empty slots will be replaced with undefined
in the new array.
with()
方法是 generic。它只期望 this
值具有 length
属性和整数键控属性。
¥The with()
method is generic. It only expects the this
value to have a length
property and integer-keyed properties.
示例
创建一个更改了单个元素的新数组
链接数组方法
在稀疏数组上使用 with()
对非数组对象调用 with()
¥Calling with() on non-array objects
with()
方法创建并返回一个新数组。它读取 this
的 length
属性,然后访问键为小于 length
的非负整数的每个属性。当访问 this
的每个属性时,索引等于该属性键的数组元素将被设置为该属性的值。最后,将 index
处的数组值设置为 value
。
¥The with()
method creates and returns a new array. It reads the length
property of this
and then accesses each property whose key is a nonnegative integer less than length
. As each property of this
is accessed, the array element having an index equal to the key of the property is set to the value of the property. Finally, the array value at index
is set to value
.
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 ]
规范
Specification |
---|
ECMAScript Language Specification # sec-array.prototype.with |
浏览器兼容性
BCD tables only load in the browser