Created
February 3, 2019 15:52
-
-
Save vogdb/efabd7f7a9559804e65722bbf0b7b731 to your computer and use it in GitHub Desktop.
Задача по копированию объектов в js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// пример глубокого копирования в Javascript. Берет на вход объект obj и возвращает его глубокую копию. | |
function deepCopy(obj) { | |
return JSON.parse(JSON.stringify(obj)); | |
} | |
// Каковы значения `o_direct`, `o_shallow`, `o_deep` в каждом нижеприведенном блоке кода? | |
// Каждый блок кода отделен друг от друга длинным комментарием `/////////////////`. | |
// Считается, что каждый блок исполняется независимо друг от друга. | |
function a_b_numbers() { | |
let a = 1; | |
let b = 2; | |
let o = {a: a, b: b}; | |
let o_direct = o; | |
let o_shallow = {...o}; | |
let o_deep = deepCopy(o); | |
///////////////// | |
o.a = 5; | |
///////////////// | |
o_direct.a = 6; | |
///////////////// | |
o_shallow.b = 7; | |
///////////////// | |
o_deep.a = 8; | |
///////////////// | |
o_deep.a = 8; | |
} | |
function a_b_arrays() { | |
let a = [1]; | |
let b = [2]; | |
let o = {a: a, b: b}; | |
let o_direct = o; | |
let o_shallow = {...o}; | |
let o_deep = deepCopy(o); | |
///////////////// | |
o.a.push(5); | |
///////////////// | |
o.a = [5]; | |
///////////////// | |
o_direct.b.push(6); | |
///////////////// | |
o_direct.b = 6; | |
///////////////// | |
o_shallow.a.push(7); | |
///////////////// | |
o_shallow.a = [7]; | |
///////////////// | |
o_deep.b.push(8); | |
///////////////// | |
o_deep.b = [8]; | |
} | |
function a_b_objects() { | |
let a = {a: 1}; | |
let b = {b: 2}; | |
let o = {a: a, b: b}; | |
let o_direct = o; | |
let o_shallow = {...o}; | |
let o_deep = deepCopy(o); | |
///////////////// | |
o.a['c'] = 3; | |
///////////////// | |
o.a = {c: 3}; | |
///////////////// | |
o_direct.b['c'] = 4; | |
///////////////// | |
o_direct.b = {c: 4}; | |
///////////////// | |
o_shallow.a['c'] = 5; | |
///////////////// | |
o_shallow.a = {c: 5}; | |
///////////////// | |
o_deep.b['c'] = 6; | |
///////////////// | |
o_deep.b = {c: 6}; | |
} | |
a_b_numbers(); | |
a_b_arrays(); | |
a_b_objects(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment