如果我创建以下代码块:
<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/