背景:
01. 作用域问题
02. 循环中变量的问题
var 作用域: 全局作用域和函数作用域
在块级作用域中等于在全局
// 块级作用域:
{
var a = 1;
// var 只遵循函数作用域,在此处申明等于在全局申明
let b = 2;
// let 仅在块级作用域里好使,在全局下会报错
console.log(b);
}
console.log(a);
for(var i = 0; i < 5; i++){
console.log(i);
没有函数的话,可能污染全局
}
console.log(i); // i被污染
let的使用:
01.不能变量声明提升:
console.log(a);// 预编译 不报错
var a = 1;
console.log(b);// 报错
let b = 2;
02.不能重复声明变量
var a = 1;
var a = 2;
console.log(a); // 被覆盖
let b = 1;
let b = 2;
console.log(b); // 报错 已经被声明过
// Uncaught SyntaxError: Lexical declaration cannot appear in a single-statement context
const的使用:
除了拥有let特性以外:
01.定义的时候要有初始化值
const a; // 报错
//Uncaught SyntaxError: Unexpected token const
const b = 2; // 不报错
02. 初始化值不能改变(绑定不能改变)
const b = 2; // 不报错
b = 3; // 报错
// Uncaught TypeError: Assignment to constant variable. 常量不能改变
const c = [1, 2, 3];
c.push(4);
// 为什么新增4不报错,因为数组的内存已经给了c,虽然新增了4,但是数组的内存并没有改变
// 如果换一个数组,就会报错
块级作用域的奇特概念:
01.暂时性死区(TDZ)
let age = 10;
{
console.log(age);// 报错,不会打印全局age,因为代码块中的age都由代码块中定义的来掌握
let age = 20;
}
// 类似:
var age = 10;
function fn() {
console.log(age);
var age = 30;
// var age提升到console.log前面,但并未初始化,在console.log下面才赋值
// 所以返回undefined
}
fn();
02.循环中使用块级作用域
var arr = [];
for(var i = 0; i < 10; i++){
arr.push(function(){ // 块级作用域代替立即执行函数
console.log(i) // 返回10个10
})
}
arr.forEach(function(item, index, arr){
item();
})
使用立即执行解决:
var arr = [];
for(var i = 0; i < 10; i++){
function(j){ //使用j接收
arr.push(function(){
console.log(j) // 得到0-9
})
}(i)) //使用i传值
}
arr.forEach(function(item, index, arr){
item();
})
使用let解决:
var arr = [];
for(let i = 0; i < 10; i++){
arr.push(function(){ // 块级作用域代替立即执行函数
console.log(i) // 得到0-9
})
}
arr.forEach(function(item, index, arr){
item();
})
JS作用域与变量管理
本文探讨了JavaScript中var、let及const关键字的作用域特性及其使用差异,包括变量声明提升、重复声明、循环中变量污染等问题,并介绍了块级作用域的概念。
824

被折叠的 条评论
为什么被折叠?



