以下是两个名为primary
和secondary
的对象:
var primary = {"gonna":3,"lol":114,"wouldn":2,"know":6,"lowkey":2,"man":5};
var secondary = primary;
当我使用delete secondary['lol'];
时,它会从两个对象中删除该属性:jsfiddle
我的问题是:如何从secondary
删除属性而不将其从primary
删除?
答案 0 :(得分:4)
secondary
引用与primary
相同的对象。如果要将它们分开,则需要创建primary
的副本。
有像Lodash这样的库,它们具有允许您克隆对象的实用程序功能(下面的示例),但是there are other ways too。
var primary = {"gonna":3,"lol":114,"wouldn":2,"know":6,"lowkey":2,"man":5};
var secondary = _.clone(primary);
delete secondary.lol;
document.write(JSON.stringify(primary));
document.write('<br>');
document.write(JSON.stringify(secondary));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
答案 1 :(得分:2)
答案 2 :(得分:1)
你应该尝试:
var primary = {"gonna":3,"lol":114,"wouldn":2,"know":6,"lowkey":2,"man":5};
var secondary = $.extend({}, primary);
delete secondary['lol'];