1

我目前正在运行 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(),但无法让它工作......所以有什么想法吗?

编辑

因此,由于我是新用户,我无法回答自己的问题,但我设法找到了解决方案。我使用了关联数组()。将最大的数组放入其中,以 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);
        }
    }
}
4

1 回答 1

0

可以chunk对数组进行处理,见以下链接

我围绕它编写了一个原型类,它解决了我的问题:

/**
 * 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();
    }
});
于 2012-06-22T12:33:11.947 回答