【问题标题】:Why does console.log wrongly print an empty array?为什么 console.log 错误地打印一个空数组?
【发布时间】:2013-08-14 11:44:02
【问题描述】:

我使用火狐。

此代码记录[]

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);

为什么会这样?

【问题讨论】:

  • 不是你的问题,但你应该更喜欢var log = console.log.bind(console); 之类的东西来保持上下文
  • 或者更好的是,使用console.log 或任何其他主机提供的功能:function log(msg) { return console.log(msg); } 主机提供的功能确实可以(并且被允许)非常松散。不能保证它们有bind,并且不能保证它们在通过其他引用而不是它们的规范引用时正常工作。
  • @T.J.Crowder,什么是主机提供的功能?
  • @learner:您在the JavaScript specification 中看不到的任何内容。所以console的各种函数,alertpromptconfirm,所有的DOM函数,...

标签: javascript firefox console.log


【解决方案1】:

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

由于你splice数组中的所有数据,几乎一登录就为空。

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

【讨论】:

  • +1 比我的答案更好的措辞和完整的解释在 30 秒内完成。 :)
  • 我现在意识到我想使用 slice 而不是 splice :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多