スプレッド演算子を使用してオブジェクトや配列の浅いコピーを作成

date
Sep 10, 2023
repo_url
slug
spread-operator-copy-objects
status
Published
summary
type
Post
thumbnail_url
tags
javascript
outer_link
const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
const person = {
    name: "Lewis",
    active: false,
}

console.log([...numbers, 9, 10]); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
console.log({ ...person, active: true }); // { name: "Lewis", active: true }
console.log({ ...person, age: 25 }); // { name: "Lewis", active: false, age: 25 }
この機能は、ReactやReact Nativeでの状態管理が必要な場合に特に便利です。
現在の状態をオブジェクトリテラルでコピーし、選択したプロパティを変更し、useStateによって提供される状態バインディングで状態を変更するだけです。
また、これは配列を連結するためや、複数のオブジェクトをマージする場合にも非常に役立ちます。それぞれのインスタンスを反復処理して手動でマージする必要がなく、一行で完了することができます。
 

© Hayato Kamiyama 2023 - 2024 - Build with Next.js & Notion