【问题标题】:Weird Javascript Outputs奇怪的 Javascript 输出
【发布时间】:2015-04-24 10:21:05
【问题描述】:

我有这个 Javascript 对象数据,我正试图将它添加到堆栈中。但是,我遇到了一些非常奇怪的错误。比如,

var data = {
    "name" : "unknown",
    "id": 1,
    "children": [ 
        {
            "name": "test",
            "id": 2,
            "children": [
                {
                    "name": "test",
                    "id": 4,
                }
            ]
        },
        {
            "name": "test",
            "id": 3
        }
    ]
};
var stack = [data];
console.log(stack); // output: undefined
while (stack.length > 0) {
    console.log(stack); // output: undefined
    var pop = stack.pop()
    console.log(stack); // output: undefined
}

我唯一能想到的是,当涉及到 while 循环时,指向堆栈对象的指针存在某种问题。

有趣的是,当我从混合中取出 while 循环或向堆栈添加索引时,会返回正常值。例如,

var stack = [data];
console.log(stack); // [Object ... ] with the correct data

var stack = [data];
console.log(stack[0]); // [Object ... ] with the correct data
while (stack.length > 0) {
    console.log(stack[0]); // [Object ... ] with the correct data
    var pop = stack.pop()
    console.log(stack); // [] as it should be...
}

有什么想法吗?

【问题讨论】:

  • console = {}; console.log = function() {}; 尝试在控制台中写入delete console
  • 使用我的 jsFiddle 日志功能一切正常。 jsfiddle.net/ifch0o1/422jfv93/1 好像是控制台问题。

标签: javascript arrays stack undefined


【解决方案1】:

如果有人使用自定义函数覆盖控制台对象,例如:console = {log: function() {}};console.log() 似乎会输出 undefined。

考虑一下:

console = {log: function() {}};
console.log(1); // undefined
delete console; // true
console.log(1); // 1

在 Chrome 中,您可以根据需要多次删除控制台对象,它会一直存在,但会删除任何自定义对象。

【讨论】:

  • 大概就是这样,事后重写控制台来发送日志到服务器是很常见的(虽然这不是一个好习惯)。
  • @Bimper 如果您在生产服务器中运行并且您的压缩器/连接器不负责删除console.log,则覆盖console 对象可能是有意义的。
猜你喜欢
  • 2012-01-23
  • 1970-01-01
  • 1970-01-01
  • 2016-03-07
  • 2021-12-03
  • 2015-02-18
  • 2011-06-14
  • 2013-06-04
  • 2021-02-08
相关资源
最近更新 更多