Array.prototype.with()
構文
js
arrayInstance.with(index, value)
引数
index
-
配列を変更するゼロ基点のインデックスで、整数に変換されます。
- インデックスが負の場合は、配列の末尾から逆に数えます。
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
プロパティを読み込み、次にキーが length
より小さい非負の整数である各プロパティにアクセスします。this
の各プロパティにアクセスすると、プロパティのキーに等しいインデックスの配列要素がプロパティの値に設定されます。最後に、配列の index
の値が value
に設定されます。
js
const arrayLike = {
length: 3,
unrelated: "foo",
0: 5,
2: 4,
3: 3, // length が 3 なので toSorted() からは無視される
};
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