js中let和var定义变量的区别
javascript严格模式
第一次接触let关键字,有一个要非常非常要注意的概念就是”javascript严格模式”,比如下述的代码运行就会报错:
lethello='helloworld.'; console.log(hello);
错误信息如下:
lethello='helloworld.'; ^^^ SyntaxError:Block-scopeddeclarations(let,const,function,class)notyetsupportedoutsidestrictmode ...
解决方法就是,在文件头添加”javascript严格模式”声明:
'usestrict'; lethello='helloworld.'; console.log(hello);
let和var关键字的异同
声明后未赋值,表现相同
'usestrict'; (function(){ varvarTest; letletTest; console.log(varTest);//输出undefined console.log(letTest);//输出undefined }());
使用未声明的变量,表现不同:
(function(){ console.log(varTest);//输出undefined(注意要注释掉下面一行才能运行) console.log(letTest);//直接报错:ReferenceError:letTestisnotdefined varvarTest='testvarOK.'; letletTest='testletOK.'; }());
重复声明同一个变量时,表现不同:
'usestrict'; (function(){ varvarTest='testvarOK.'; letletTest='testletOK.'; varvarTest='varTestchanged.'; letletTest='letTestchanged.';//直接报错:SyntaxError:Identifier'letTest'hasalreadybeendeclared console.log(varTest);//输出varTestchanged.(注意要注释掉上面letTest变量的重复声明才能运行) console.log(letTest); }());
变量作用范围,表现不同
'usestrict'; (function(){ varvarTest='testvarOK.'; letletTest='testletOK.'; { varvarTest='varTestchanged.'; letletTest='letTestchanged.'; } console.log(varTest);//输出"varTestchanged.",内部"{}"中声明的varTest变量覆盖外部的letTest声明 console.log(letTest);//输出"testletOK.",内部"{}"中声明的letTest和外部的letTest不是同一个变量 }());
总结
以上所述是小编给大家介绍的js中let和var定义变量的区别,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!