JavaScriptでオブジェクトをコピーするためのさまざまな手法
オブジェクトを任意の言語でコピーするには、ディープコピーとシャローコピーの2つの方法があります。
浅いコピーと深いコピーは言語に依存しません。浅いコピーは可能な限り複製しません。コレクションの浅いコピーは、要素ではなく、コレクション構造のコピーです。浅いコピーで、2つのコレクションが個々の要素を共有するようになりました。
例
let innerObj = {
a: 'b',
c: 'd'
}
let obj = {
x: "test",
y: innerObj
}
// Create a shallow copy.
let copyObj = Object.assign({}, obj);
// Both copyObj and obj's prop y now refers to the same innerObj. Any changes to this will be reflected.
innerObj.a = "test"
console.log(obj)
console.log(copyObj) 出力
これにより、出力が得られます-
{ x: 'test', y: { a: 'test', c: 'd' } }
{ x: 'test', y: { a: 'test', c: 'd' } } 浅いコピーは再帰的にクローンを作成しないことに注意してください。トップレベルでそれを行うだけです。
ディープコピーはすべてを複製します。コレクションのディープコピーは、元のコレクションのすべての要素が複製された2つのコレクションです。
例
let innerObj = {
a: 'b',
c: 'd'
}
let obj = {
x: "test",
y: innerObj
}
// Create a deep copy.
let copyObj = JSON.parse(JSON.stringify(obj))
// Both copyObj and obj's prop y now refers to the same innerObj. Any changes to this will be reflected.
innerObj.a = "test"
console.log(obj)
console.log(copyObj) 出力
これにより、出力が得られます-
{ x: 'test', y: { a: 'test', c: 'd' } }
{ x: 'test', y: { a: 'b', c: 'd' } } -
JavaScriptのオブジェクトの同等性を説明します。
JavaScriptでは、文字列、数値、ブール値などのプリミティブはそれらの値によって比較され、オブジェクト(ネイティブまたはカスタム)はそれらの参照によって比較されます。参照による比較とは、2つ以上のオブジェクトがメモリ内の同じ場所を指しているかどうかを意味します。 以下は、JavaScriptのオブジェクトの同等性を説明するコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name=&q
-
JavaScriptのオブジェクトにreduceメソッドを適用するにはどうすればよいですか?
以下は、JavaScriptのオブジェクトにreduceメソッドを適用するためのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <sty