gpt4 book ai didi

javascript - 从克隆的 JavaScript 对象中删除键会改变原始对象

转载 作者:行者123 更新时间:2023-11-28 19:06:24 24 4
gpt4 key购买 nike

我有一个非常大的 JSON 事件源,我通过 AJAX 将其拉入 JavaScript。一旦我在内存中拥有该对象,我就希望能够使用它,而不是每次都进行新的 AJAX 调用。

我有一个允许过滤 JSON 事件的表单。在初始过滤时,我的函数会复制原始对象(以保留它),然后在新对象与过滤条件不匹配时从新对象中删除键。

这组函数第一次运行时效果很好。然而,当再次运行时,原始对象似乎被更改,然后触发 JavaScript 错误。

当我console.debug原始对象时,我可以看到它第一次运行时,它是一个预期的对象。在进一步的运行中,看起来它正在以某种方式转换为对象数组。

我简化了代码以在此处显示问题:

json = [{"title": "Title 1","time": 1},{"title": "Title 2","time": 1},{"title": "Title 3","time": 2},{"title": "Title 4","time": 2},{"title": "Title 5","time": 3},{"title": "Title 6","time": 3},{"title": "Title 7","time": 4},{"title": "Title 8","time": 4},{"title": "Title 9","time": 5},{"title": "Title 10","time": 5}];
jQuery('a').on('click touch tap', function(){
propEvents(json);
return false;
});
//End prep code for example


function propEvents(json){
var loadFromMemory = 0;

if ( loadFromMemory == 0 ){
globalEventObject = json;
loadFromMemory = 1;
}


console.log('Initial Global Object:');
console.debug(globalEventObject);

//Filter the JSON
filteredEventsObject = eventSearch(globalEventObject);

//The global object was never filtered, but keys are being removed from it too... I need to store it in memory to start filters from scratch each time.
console.log('Global Object After Filter:');
console.debug(globalEventObject);
}


function eventSearch(events){
var tempObject = events; //May be unnecessary, but for example purposes.

jQuery(tempObject).each(function(i){
if ( tempObject[i].time != 3 ){
console.log('no match: removing this event');
delete tempObject[i]; //Remove this key from the tempObject
return;
}
});

tempObject = tempObject.filter(function(){return true;}); //Start the keys from 0 again.
console.log('Length of filtered object:');
console.debug(tempObject.length);
return tempObject;
}

Here it is in CodePen您可以在其中查看控制台日志。这让我忙了几天,但我就是无法理解它。任何线索将不胜感激。

最佳答案

var tempObject = events;实际上并不克隆该对象。相反,它使 var tempObject 指向 events,随后,对 tempObject 产生的任何副作用也会发生在 events.

有很多方法可以克隆对象,请参阅这个SO问题以了解详细信息:What is the most efficient way to deep clone an object in JavaScript?

既然你提到你正在尝试操作 JSON feed,我建议

var clone = JSON.parse(JSON.stringify(events))

并操作克隆

关于javascript - 从克隆的 JavaScript 对象中删除键会改变原始对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31571696/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com