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

bat*_*man 0 javascript firefox console.log

我用的是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);
Run Code Online (Sandbox Code Playgroud)

此代码记录正确的值.

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);
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

Que*_*tin 11

console.log显示实时数据,而不是运行时对象的快照.

由于您splice从阵列中获取了所有数据,因此几乎在您记录它时就会为空.

如果要记录数组的快照,请对其进行字符串化或深层复制.

  • +1更好的措辞,并在30秒内完全解释,比我的答案少.:) (2认同)
  • 我现在意识到我想使用`slice`而不是`splice` :) (2认同)