
在 javascript 中,let、const 和 var 用来声明变量,但它们在三个方面有所不同:
1.范围
2.重新分配
3.吊装
var 是一个函数作用域,意味着我们在函数内的任何位置访问 var 变量,如果我们尝试在函数外部访问它,它将显示错误 undefined
示例:-
function demo(){
if(true){
var n = 3;
}
console.log(n)
}
console.log(n) //referenceerror: n is not defined
demo();
let & const 是块意味着我们只能在范围内访问它们,否则会显示未定义的错误
示例:-
function demo(){
if(true){
let n = 3;
const m = 5;
console.log(n) // 3
console.log(m) // 5
}
console.log(n) //referenceerror: n is not defined
console.log(m) //referenceerror: n is not defined
}
console.log(n) //referenceerror: n is not defined
console.log(m) //referenceerror: n is not defined
demo();
// var example console.log(a); // undefined (due to hoisting) var a = 10; console.log(a); // 10 // let example console.log(b); // ReferenceError: Cannot access 'b' before initialization let b = 20; console.log(b); // 20 // const example const c = 30; c = 40; // TypeError: Assignment to constant variable
以上就是JavaScript 中 let、const、var 的区别?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号