为什么console.log错误地打印了一个空数组

Why does console.log wrongly print an empty array?

本文关键字:一个 数组 log console 错误 打印 为什么      更新时间:2023-09-26

我使用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阵列中的所有数据,所以几乎一登录它,它就为空

如果您想记录阵列的快照,请对其进行字符串化或深度复制。