簡體   English   中英

為什么console.log錯誤地打印一個空數組?

[英]Why does console.log wrongly print an empty array?

我使用Firefox。

此代碼記錄為[]

var log = console.log;

function new_comb(aComb) {
    var res = [];
    log(aComb); // <- This is the line
    for (var p in aComb) {
        var peg = aComb[p];
        var current = peg[peg.length - 1];
        for (var i = 0; i < aComb.length; i++) {
            if (i == p) continue;
            if (current > aComb[i][aComb[i].length - 1]) continue;
            var tmp = aComb.splice(0);
            tmp[i].push(current);
            tmp[p].pop();
            res.push(tmp);
        }
    }
    return res;
}

var comb = [
    [3, 1],
    [9, 2],
    [15, 0]];
var res = new_comb(comb);

此代碼記錄正確的值。

var log = console.log;

function new_comb(aComb) {
    var res = [];
    log(aComb); // <- This is the line
    // note that I comment this out.
    /*for (var p in aComb) {
        var peg = aComb[p];
        var current = peg[peg.length - 1];
        for (var i = 0; i < aComb.length; i++) {
            if (i == p) continue;
            if (current > aComb[i][aComb[i].length - 1]) continue;
            var tmp = aComb.splice(0);
            tmp[i].push(current);
            tmp[p].pop();
            res.push(tmp);
        }
    }*/
    return res;
}

var comb = [
    [3, 1],
    [9, 2],
    [15, 0]];
var res = new_comb(comb);

為什么會這樣呢?

console.log顯示實時數據,而不是對象的快照。

由於您將所有數據splice出陣列,因此幾乎在您記錄日志后就將其清空。

如果要記錄陣列的快照,則對陣列進行字符串化或深度復制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM