对象的javascript数组推送值
我试图创建一个对象数组,但是当我推到数组上时,它会向对象添加一个引用,而不是复制值对象的javascript数组推送值,javascript,arrays,reference,Javascript,Arrays,Reference,我试图创建一个对象数组,但是当我推到数组上时,它会向对象添加一个引用,而不是复制值 var nestedOrgList = []; var tempTopOrg = {}; var i = 0; while (typeof divList[i] !== 'undefined') { tempTopOrg.org = divList[i++]; // increment i after we assign this tempTopOrg.suborgs = []; wh
var nestedOrgList = [];
var tempTopOrg = {};
var i = 0;
while (typeof divList[i] !== 'undefined') {
tempTopOrg.org = divList[i++]; // increment i after we assign this
tempTopOrg.suborgs = [];
while ($(divList[i]).has('.expand').length < 1 && i < divList.length) {
tempTopOrg.suborgs.push(divList[i++]);
}
nestedOrgList.push(tempTopOrg);
};
如果速度不是一个关键目标,一种常见的方法是使用JSON对对象进行编码/解码:
var json = JSON.stringify(tempTopOrg);
nestedOrgList.push( JSON.parse(json) );
javascript通过引用传递对象和数组,因此您必须在推之前进行复制
myarray.push(JSON.parse(JSON.stringify(obj)));
又快又脏,可能有性能问题
尝试解决对象克隆问题。您可以检查以下答案 JSperf
显然JavaScript应该有一种本地复制引用的方法。使用深度复制
var newcopy = temp.slice(0);
要过滤未定义和空值,请使用
newcopy = newcopy.filter(function(e){ return e });
@NuclearHost JavaScript传递值(提示:对象是值),并且,与赋值过程一样,这些值不会在过程中被复制/克隆/复制。ECMAScript规范中没有使用“引用”来描述此行为。感谢您对该答案的引用
newcopy = newcopy.filter(function(e){ return e });