为什么console.log错误地打印一个空数组? [英] Why does console.log wrongly print an empty array?

查看:74
本文介绍了为什么console.log错误地打印一个空数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Firefox。



此代码记录 []

  var log = console.log; 

函数new_comb(aComb){
var res = [];
log(aComb); //<--这是
行(aComb中的var p){
var peg = aComb [p];
var current = peg [peg.length-1];
for(var i = 0; i< aComb.length; i ++){
如果(i == p)继续;
如果(当前> aComb [i] [aComb [i] .length-1])继续;
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; 

函数new_comb(aComb){
var res = [];
log(aComb); //<-这是
行//请注意,我已对此进行注释。
/ * for(aComb中的var p){
var peg = aComb [p];
var current = peg [peg.length-1];
for(var i = 0; i< aComb.length; i ++){
如果(i == p)继续;
如果(当前> aComb [i] [aComb [i] .length-1])继续;
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 数组中的所有数据,几乎在您记录后就为空。 / p>

如果要记录阵列的快照,则对阵列进行字符串化或深度复制。


I use Firefox.

This code logs [].

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

This code logs the correct value.

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

Why is this happening?

解决方案

console.log shows live data, not a snapshot of the object at the time you run it.

Since you splice all the data out of the array, it is empty almost as soon as you log it.

Stringify or deep copy the array if you want to log a snapshot of it.

这篇关于为什么console.log错误地打印一个空数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆