2 回答

TA貢獻(xiàn)2080條經(jīng)驗(yàn) 獲得超4個贊
為什么會這樣?
這是因?yàn)樽兞刻嵘?/p>
所以這
window.test1 = 'Jack';
setInterval(function(){
var test1 = test1 || [];
console.log(test1); // Works bad, get [] instead of "Jack"
}, 2000);
實(shí)際上是這個
window.test1 = 'Jack';
setInterval(function(){
// declaring local variable test1 and it has no value so it holds `undefined`
var test1;
// so now you gett [] instead because the variable test1 is falsy `undefined`
test1 = test1 || [];
console.log(test1); // Works bad, get [] instead of "Jack"
}, 2000);

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個贊
test1
發(fā)生這種情況是因?yàn)槟诤瘮?shù)和變量提升中聲明了變量。使用您的示例和修改后的版本,我們可以看到第一個超時函數(shù)顯示的結(jié)果與我們預(yù)期的結(jié)果相同,避免此問題的一種方法是第二個超時函數(shù)中的示例(使用不同的變量描述符):
window.test1 = 'Jack';
setTimeout(function() {
? var test1 = test1 || [];
? console.log('timeoutFunction1', test1); // Works bad, get [] instead of "Jack"
}, 2000);
setTimeout(function() {
? var test2 = test1 || []; // Works fine since we're not declaring `test1` in this function
? console.log('timeoutFunction2', test2);
}, 3000);
添加回答
舉報