語法
js
arrayInstance.with(index, value)
引數
index-
要更改陣列的零基索引,將該索引轉換為整數。
- 負數索引從陣列末尾開始計數——如果
-array.length <= index < 0,則使用index + array.length。 - 如果規範化後的索引超出範圍,將丟擲
RangeError。
- 負數索引從陣列末尾開始計數——如果
value-
要賦給給定索引的任何值。
返回值
一個新陣列,其中 index 處的元素被 value 替換。
異常
RangeError-
如果
index >= array.length或index < -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() 方法會建立並返回一個新陣列。它讀取 this 的 length 屬性,然後訪問鍵小於 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 |
瀏覽器相容性
載入中…