2 回答
TA貢獻2080條經驗 獲得超4個贊
為什么會這樣?
這是因為變量提升
所以這
window.test1 = 'Jack';
setInterval(function(){
var test1 = test1 || [];
console.log(test1); // Works bad, get [] instead of "Jack"
}, 2000);
實際上是這個
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貢獻1827條經驗 獲得超9個贊
test1發生這種情況是因為您在函數和變量提升中聲明了變量。使用您的示例和修改后的版本,我們可以看到第一個超時函數顯示的結果與我們預期的結果相同,避免此問題的一種方法是第二個超時函數中的示例(使用不同的變量描述符):
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);
添加回答
舉報
