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 }
刚开始接触 不是很明白,希望有知道的说明下原因
高洛峰2017-04-21 11:18:56
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...
ringa_lee2017-04-21 11:18:56
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.
迷茫2017-04-21 11:18:56
Yes, this is purely a Javascript syntax issue. This problem exists in Javascript. That is, the problem of deep copy and shallow copy:
var cloneObj = function(obj){
var str, newobj = obj.constructor === Array ? [] : {};
if(typeof obj !== 'object'){
return;
} else if(window.JSON){
str = JSON.stringify(obj), //系列化对象
newobj = JSON.parse(str); //还原
} else {
for(var i in obj){
newobj[i] = typeof obj[i] === 'object' ?
cloneObj(obj[i]) : obj[i];
}
}
return newobj;
};
Code transferred from https://www.zhihu.com/question/23031215