{ let a = 1 var b = 2 } console.log(a) //Uncaught ReferenceError: a is not defined 未捕获引用错误:a是未定义 console.log(b) //2
{ let a = 1; let a = 2; var b = 3; var b = 4; } console.log(a) //Uncaught SyntaxError: Identifier ‘a‘ has already been declared 未捕获的语法错误:已声明标识符“a” console.log(b) //4
for (var i = 0; i < 10; i++) { setTimeout(function () { console.log(i); //10次10 }) } for (let j = 0; j < 10; j++) { setTimeout(function () { console.log(j); //0123456789 }) }
for (var i = 0; i < 3; i++) { var i = ‘abc‘; console.log(i); //输出一次abc } for (let j = 0; j < 3; j++) { let j = ‘abc‘; console.log(j); //输出三次abc }
console.log(b); // 输出undefined var b = 2;
console.log(a); // 报错Uncaught ReferenceError: Cannot access ‘a‘ before initialization未捕获的引用错误:无法在初始化之前访问“a” let a = 2;
var a = 123; if (true) { //console.log(a) //Uncaught ReferenceError: Cannot access ‘a‘ before initialization 未捕获的引用错误:无法在初始化之前访问“a” a = ‘abc‘; let a; //console.log(a) }
typeof x; // Uncaught ReferenceError: Cannot access ‘x‘ before initialization 未捕获的引用错误:无法在初始化之前访问“x” let x; console.log(typeof x)
上面代码中,变量x使用let命令声明,所以在声明之前,都属于x的“死区”,只要用到该变量就会报错。因此,typeof运行时就会抛出一个ReferenceError。
typeof y console.log(typeof y) //undefined
function bar(x = y, y = 2) { return [x, y]; } console.log(bar()) // 报错Uncaught ReferenceError: Cannot access ‘y‘ before initialization 未捕获的引用错误:无法在初始化之前访问“y” function bar(x = 2, y = x) { return [x, y]; } console.log(bar())// [2, 2]
var x = x; console.log(x) // 不报错 let y = y; console.log(y) // ReferenceError: y is not defined y是未定义的
const a = 123; a = 3; console.log(a) //Uncaught TypeError: Assignment to constant variable. 上面代码表明 未捕获类型错误:分配给常量变量。
const a; console.log(a) // SyntaxError: Missing initializer in const declaration const声明中缺少初始值设定项
if (true) { const a = 5; } console.log(a) //Uncaught ReferenceError: a is not defined a是未定义的
if (true) { console.log(a); // Uncaught ReferenceError: Cannot access ‘a‘ before initialization 未捕获的引用错误:无法在初始化之前访问“a” const a = 5; }
const a = []; a.push(‘Hello‘); // 可执行 a.length = 0; // 可执行 a = [‘Dave‘]; // 报错Uncaught TypeError: Assignment to constant variable. 未捕获类型错误:分配给常量变量。
原文:https://www.cnblogs.com/shy0113/p/11862876.html