JavaScript Fundamentals: Reference VS Copy #JavaScript30 14/30

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

last concept of deep clone is truly awesome

singhkr
Автор

Great lesson for JS newbies and great reminder for me.

djvesko
Автор

very useful, just wanted to add that when using Object.assign, one can add desired properties directly inside of its first param, instead of making it an empty obj and using 3rd to add params. For example: Object.assign({}, wes, {age:26}) can be done like this: Object.assign({age:26}, wes)

bokisa
Автор

Any reason why at 5:45, array.map() method isn't used when using the other ES6 methods?

franciscalizo
Автор

All those methods of copying arrays make shallow copies. For example:

let ar1 = [1, 2, 3, ['a', 'b', 'c'], 5, 6];
let ar2 = ar1.slice();

ar2[3][1] = "BOO!"

console.log(ar1); // :(

In order to make deep copies, one needs to make a recursive function, for example:

function copyArray(arr) {
let copy;
if (null == arr || "object" != typeof arr) return arr;
if (arr instanceof Array) {
copy = [];
for (const item of arr) {
copy.push(copyArray(item));
}
return copy;
}
throw new Error("Unexpected data type");
}

Автор

Wes, const cap3 ={...person}; worked for me...

kisanb
Автор

bro would be happy to know that object spread do exists now

mriduljain
Автор

What about for in? I just note that isn't a deep object copy, but works well for arrays

ZarateAdriel
Автор

the copy / assignation in arrays and objects that doesn't happen in strings and number, is about mutability ?

ZarateAdriel
Автор

Deep Clone function if anyone needs it
function cloneObject(obj) {
var clone = {};
for(var i in obj) {
if(obj[i] != null && typeof(obj[i])=="object")
clone[i] = cloneObject(obj[i]);
else
clone[i] = obj[i];
}
return clone;
}

animeshsingh
welcome to shbcf.ru