Javascript console.log 在设置之前打印值

标签 javascript

如果我创建以下代码块:

<script language="JavaScript" type="text/javascript" src="jquery-2.1.1.js"></script>
<script type = "text/javascript">
x = [1,2,3,4,5,6]
new_list = []
for (i = 0; i < x.length-1; i++) {
    var links = {}
    console.log("first:", links)

    for (j = i+1; j < x.length; j++) {
        links["source"] = i
        links["target"] = j
    }
}
//document.write('<b>End of script.</b>');
</script>

理论上,控制台应该打印 {}, {source: 0, target 1}, {source: 0, target: 2}, ... 实际上,它打印:

"first:" {source: 1, target: 5} Test1.html:7
"first:" {source: 2, target: 5} Test1.html:7
"first:" {source: 3, target: 5} Test1.html:7
"first:" {source: 4, target: 5}

为什么会发生这种情况? 'target' 第一次打印时的值怎么会是 5?第一个打印的东西不应该是一个空的关联数组吗?

最佳答案

实际上,正如您在这里看到的:https://developer.mozilla.org/en-US/docs/Web/API/console

The console object provides access to the browser's debugging console (e.g. the Web Console in Firefox). The specifics of how it works vary from browser to browser, but there is a de facto set of features that are typically provided.

标准中未指定 window.console 对象(以及 window.console.log)行为。 “奇怪”的行为不是由于您的代码(它完全按照您的预期执行),而是由于 console.log 延迟评估(至少在您的浏览器中)。

<小时/>

运行这个 fiddle :http://jsfiddle.net/6dQB8/

在 Firefox30 中输出:

"first:" Object { source: 0 } _display:25
"first:" Object { source: 1 } _display:25
"first:" Object { source: 2 } _display:25
"first:" Object { source: 3 } _display:25
"first:" Object { source: 4 } _display:25

在 IE10 中输出

File: jsfiddle.net first: [object Object] "first:" { [functions]: , proto: { } }

first: [object Object] "first:" { [functions]: , proto: { } }

first: [object Object] "first:" { [functions]: , proto: { } }

first: [object Object] "first:" { [functions]: , proto: { } }

first: [object Object] "first:" { [functions]: , proto: { } }

(所以,在 Firefox 中我总是得到“source”的值,在 IE10 中我总是记录一个空对象)

结论:使用可变对象时不要依赖 console.log : )

关于Javascript console.log 在设置之前打印值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24627407/

相关文章:

javascript - 如何在 Google Chrome 控制台中访问由 3rd 方 API 检索到的 JSON 数据?

javascript - javascript 中的函数在调用时不起作用

javascript - Angular 5中 "tick"是什么意思

javascript - 在 slider 中居中 ResponsiveSlides 导航箭头?

javascript - 如何将提交监听器附加到所有表单,包括 iframe 和嵌套 iframe 中的表单

javascript - Facebook oauth javascript 重定向导致无限循环

Javascript setInterval - 如何设置良好的时间和性能

将javascript数组放入div

javascript - 警告 : Cannot update during an existing state transition

javascript - 根据容器更改而不是窗口大小调整 Highcharts 大小