我的变量的内容为空(在代码的开头),因为在代码的底部调用了.empty()方法。为什么呢?
<div id="fixture"></div>
<script>
"use strict";
var GREETING_INPUT = "<input type='text' class='js-greeting-input' />";
var GREETING_MESSAGE = "<div class='js-greeting-message'></div>";
var $fixture = $("#fixture");
console.log("before");
$fixture.append(GREETING_INPUT);
// $fixture is empty!
// if we remove "$fixture.empty()" at the bottom, $fixture is not empty.
console.log($fixture);
console.log("after");
$fixture.empty();
console.log($fixture);
</script>
答案 0 :(得分:4)
这是控制台。当您转储对象时,控制台(有时)会显示该对象的实时副本,因此如果您在所有代码运行后查看它,则该实时副本已更新。控制台显示器不像终端窗口;浏览器(可能)会更新它所显示的内容。
因此,$fixture
之后的第二个console.log
,append
并不是空的,而是您稍后$fixture.empty()
时更新了控制台。
答案 1 :(得分:3)
控制台不是人们可能认为的平面文本输出设备。相反,当您记录对象时,您要求对要放置在输出窗口中的对象进行动态引用 - 而不是像记录时那样的对象快照。
当empty
jQuery对象时,您已经记录的动态引用反映了这一点。
如果您能够在第一个日志语句后暂停执行,您会看到您的变量包含您所期望的内容。但是,其他代码在您有机会之前运行。
就像下面这样:
var a = {value: true};
var c = a; // "logging" a
delete a.value; // emptying a
// examine c and it is empty