指定されたインデックス位置の配列の要素の値を取得,設定する - at, with

《 初回公開:2023/10/19 , 最終更新:未 》

at

指定されたインデックス位置の配列の要素の値を取得する。

構文
array.at(index)
引数
index
取得する要素のインデックス位置を指定。
負の値を指定した場合、配列の末尾からの相対的な位置つまりarray.length + indexを指す。
インデックス位置が配列のインデックス範囲外の場合はundefinedを返す。
戻り値
インデックス位置の要素の値を返す
const array = ["a", "b", "c"];

console.log(array.at(1));   // array[1] -> b

負の値を指定すると、配列の末尾からの相対的な位置を示す事。

console.log(array.at(-1));  // array[length-1] -> c

範囲外の値を指定するとundefinedを返す。

console.log(array.at(10));  // undefined

with

元の配列を変更せずに元の配列の指定したインデックス位置の要素の値を置き換えた新しい配列を生成して返すコピーメソッド(非破壊的メソッド)。

構文
array.with(index, value)
引数
index
要素の値を置き換えるインデックス位置を指定。
負の値を指定した場合、配列の末尾からの相対的な位置つまりarray.length + indexを指す。
インデックス位置が配列のインデックス範囲外の場合はエラーが発生する。
value
置き換える要素の値を指定。
戻り値
インデックス位置の要素の値を置き換えた新しい配列を生成して返す

{
    const array = ["a", "b", "c"];
    const result = array.with(1, "x");
    console.log(array, result); // ["a", "b", "c"] ["a", "x", "c"]
}
{
    // index引数に負の値を指定
    const array = ["a", "b", "c"];
    const result = array.with(-2, "x");
    console.log(array, result); // ["a", "b", "c"] ["a", "x", "c"]
}
{
    // インデックスが配列の範囲外の場合
    const array = ["a", "b", "c"];
    // エラーが発生する
    const result = array.with(-4, "x"); // Uncaught RangeError: Invalid index : -4
}

元の配列がスパース配列の場合、空のスロットはundefinedに置き換えられる。

const array = ["a", ,"c", ,"e"];
const result = array.with(1, "b");

console.log(array, result); // ['a', なし, 'c', なし, 'e'] ['a', 'b', 'c', undefined, 'e']
// 元の配列には要素3のプロパティは存在しない。
console.log(array.hasOwnProperty(3));   // false
// 新しく生成された配列は要素3のプロパティにはundefinedが格納されている。
console.log(result.hasOwnProperty(3));  // true

array-like objectの結果は配列に置き換えられる。

const arrayLike = {
    0: "a",
    1: "b",
    2: "c",
    length: 3,
};
const result = (Array.prototype.with.call(arrayLike, 1, "x"));
console.log(arrayLike, result); // {0: 'a', 1: 'b', 2: 'c', length: 3} ['a', 'x', 'c']
console.log(Array.isArray(result)); // true
ページのトップへ戻る