db.mongo.insert({name:'mongo'}); > var t=db.mongo.findOne(); > t { "_id" : ObjectId("5141b98723616e67f947f356"), "name" : "mongo" } > var d=t > d { "_id" : ObjectId("5141b98723616e67f947f356"), "name" : "mongo" } > d.password=123 123 > d { "_id" : ObjectId("5141b98723616e67f947f356"), "name" : "mongo", "password" : 123 } > t { "_id" : ObjectId("5141b98723616e67f947f356"), "name" : "mongo", "password" : 123 }
问题1
var d = t
是引用赋值吗 如果是的话,怎么样不使用引用赋值
delete d.password true > d { "_id" : ObjectId("5141b98723616e67f947f356"), "name" : "mongo" } > d.password=124 124 > d { "_id" : ObjectId("5141b98723616e67f947f356"), "name" : "mongo", "password" : 124, "password" : 124 }
问题2 我执行
delete d.password
返回 true 说明已经删除,为什么我再执行
d.password=124
会执行两次添加
> d { "_id" : ObjectId("5141b98723616e67f947f356"), "name" : "mongo", "password" : 124, "password" : 124 }
刚开始接触 不是很明白,希望有知道的说明下原因
The first question... Because the two entries have the same
ObjectId
, they are regarded as the same one...Although it is not actually a reference assignment, you can understand it this way...
The second problem cannot be reproduced, so I don’t know...
This is either the same problem with ObjectId, or simply JavaScript syntax requires reference assignment. If you want to clone, watch this. http://stackoverflow.com/questions/122102/most-efficient-way-to-clone-an-object
I haven’t encountered the second problem either.
Yes, this is purely a Javascript syntax issue. This problem exists in Javascript. That is, the problem of deep copy and shallow copy:
Code transferred from https://www.zhihu.com/question/23031215