我正在运行2个for循环,通过2个对象数组并创建一个新数组,其中包含两个列表中出现的对象。当列表变得很大时,我会收到“停止运行脚本”提示。
MineGlobals.receivedData = jQuery.parseJSON(MineGlobals.receivedDataRaw);
MineGlobals.nettStasjonsListe = new Array();
var len1 = MineGlobals.nsData.length;
var len2 = MineGlobals.receivedData.Nettstasjoner.length
for (var i = 0; i < len2; i++) {
for (var j = 0; j < len1; j++) {
if (MineGlobals.receivedData.Nettstasjoner[i].Id == MineGlobals.nsData[j].Id) {
var obj = new nsObject();
obj = MineGlobals.nsData[j];
if (MineGlobals.nsData[j].Lg != 0 && MineGlobals.nsData[j].La != 0) {
MineGlobals.nettStasjonsListe.push(obj);
}
break;
}
}
}
我尝试使用setTimeout(),但无法让它工作......那么任何想法?
修改
因为我是新用户,我无法回答我自己的问题,但我找到了解决方案。我使用了associativeArray()。将最大的数组放入其中,将ID作为键,然后迭代它以查找相同的ID。
var associativeArray = {};
for (var i = 0; i < len1; i++) {
associativeArray[MineGlobals.nsData[i].Id] = MineGlobals.nsData[i];
}
for (var j = 0; j < len2; j++) {
var obj = new nsObject();
obj = associativeArray[MineGlobals.receivedData.Nettstasjoner[j].Id];
if (obj != undefined) {
if (obj.Lg != 0 && obj.La != 0) {
if (obj == null || obj == "") {
obj.Nvn = "Ikke definert";
}
if (obj.NisAdresse == null || obj.NisAdresse == "") {
obj.NisAdresse = "Ikke definert";
}
MineGlobals.nettStasjonsListe.push(obj);
}
}
}
答案 0 :(得分:0)
您可以chunk
进行数组处理,请参阅以下link:
我围绕它编写了一个原型类,它解决了我的问题:
/**
* provides UI update while using large arrays without blocking
* found core idea on http://www.mattsnider.com/javascript/handle-slow-processes-without-blocking-the-ui/
*/
var ChunkedArray = Class.create(Enumerable, {
initialize: function(options) {
this.array = new Array();
this.options = Object.extend({
chunkSize: 20,
interval: 10
}, options || {})
},
push: function(obj) {
this.array.push(obj)
},
chunk: function(array, index, length, iterator, context) {
var j, l = array.length;
for (j = (index + length); (index < j && index < l); index += 1) {
iterator.call(context, array[index], index);
}
if (l > index) {
setTimeout(function() {
this.chunk(array, index, length, iterator, context);
}.bind(this), this.options.interval);
}
},
_each: function(iterator, context) {
this.chunk(this.array, 0,
this.options.chunkSize, iterator, context);
},
toString: function() {
return this.array.toString();
}
});