Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

再问一个js里面的一个新手小问题,关于声明变量

bbb="888"
console.log(bbb)
let bbb
//为什么会输出bbb is not defined,let声明不是不会提升么,应该输出888呀

var a = 1;
function foo(){
if(false){

   var a = 2;
   console.log("333")

}
console.log(a)
}
foo();//为什么会输出undifined,上面是if(false)判断为假,应该不会执行呀,

for(let i = 0;i < 2; i++){
//console.log(i);
setTimeout(function () {//同步注册回调函数到异步的宏任务队列

console.log(i);//执行此代码时,for循环已经执行完毕。

},0);
}//如果多次执行,为什么前面会输出2,4,6 。这是什么诶image


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. 会输出Cannot access 'bbb' before initialization, 虽然let不会声明提升,但是会有一个暂时性死区,在声明之前会报错。
  2. 会输入undefined,是因为var有声明提升没什么好说的。
  3. 2,4,6是setTimeout返回值,不要纠结。

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...