简体   繁体   中英

Assigning an object to another variable

I'm learning JavaScript and noticed when a variable is assigned to another variable, it does not copy the contents of it, rather becomes the extension of same variable. For example:

var data1 = {"name": "john", "age": 34, "city": "london"}

var data2 = data1

delete data2.city

console.log(data1)
{"name": "john", "age": 34}

The above code will not only delete the city property from data2 but also from data1 .

How should I only COPY the contents into data2 from data1 and change it without disturbing the data1 ?

您的变量指向同一对象。

var data2 = Object.assign({}, data1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM