![](/img/trans.png)
[英]Why is js object not empty in console.log before being assigned?
[英]Why does console.log log a value before it's assigned?
一個簡短的例子:
self.curTabs = null;
$j.getJSON(url)
.done(function (response) {
self.curTabs = response.tabs;
_.each(self.curTabs, function (tab) {
tab.dataLoaded = true;
});
console.log(self.curTabs);
});
邏輯輸出: [ 0: Object { dataLoaded: true, etc... }, 1: etc... ]
。
但是這個例子:
self.curTabs = null;
$j.getJSON(url)
.done(function (response) {
self.curTabs = response.tabs;
_.each(self.curTabs, function (tab) {
tab.dataLoaded = true;
});
console.log(self.curTabs);
_.each(self.curTabs, function (tab) {
tab.dataLoaded = false;
});
});
不合邏輯的輸出: [ 0: Object { dataLoaded: false, etc... }, 1: etc... ]
。
為什么變量在賦值之前得到的值為false
?
因為console.log在每個實現中都不是同步的。 這樣它排隊直到主線完成。 在此期間,您的新值已設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.