for (let i = 0; i < 2; i ++){
console.log('inner',i);
}
console.log('**************');
i =-1;
if( i < 2) {
console.log('inner',i);
i = i +1;
if( i < 2){
console.log('inner',i);
i = i +1;
if( i < 2){
console.log('inner',i);
i = i +1;
} else {
return ;
}
} else {
return ;
}
}
上面的代码是正确的。
这是结果。
内在0 内在的1 **************
内-1 内部0
内心1
当我编写以下代码时,会发生此错误 为
的console.log(&#39;内&#39; I,);
^ ReferenceError:我没有定义
for (let i = 0; i < 2; i ++){
console.log('inner',i); // i is not defined
let i = 100;
}
console.log('**************');
i =-1;
if( i < 2) {
console.log('inner',i); // i is not defined
let i = 100;
i = i +1;
if( i < 2){
console.log('inner',i);
i = i +1;
if( i < 2){
console.log('inner',i);
i = i +1;
} else {
return ;
}
} else {
return ;
}
}
答案 0 :(得分:2)
The standard说,“让和 const 声明定义范围限定为正在运行的执行上下文的LexicalEnvironment的变量。变量是在包含词法环境时创建的实例化,但在评估变量的LexicalBinding之前,可能无法以任何方式访问它。“
当阻止
SELECT * FROM Orders
WHERE (CustomerID <> 51 AND ShipperID <> 3)
OR (CustomerID = 51 AND ShipperID <> 3);
执行:
{ // 0
console.log('inner',i); // 1
let i = 100; // 2
}
。i
的使用是指新实例化的词法环境中名为i
的变量。但是,由于第2行的词法绑定尚未执行,因此访问此变量是错误的。答案 1 :(得分:0)
正如@Jai所提到的,let
关键字仅在其创建的块范围内定义。因此,让我们看看您的代码:
for (let i = 0; i < 2; i ++){ // i is declared using let so it can only be used inside of this for loop
console.log('inner',i);
let i = 100; // Here you're re-declaring i for some reason? This could be the cause of i being undefined on the above line
}
console.log('**************');
i =-1; // Here you're trying to access i outside the for loop, but since it's outside it's not defined
if( i < 2) {
console.log('inner',i); // i is not defined, same reason as previously
let i = 100; // However here you declare i again, so the next console.log will not cause an error
i = i +1;
if( i < 2){
console.log('inner',i);
i = i +1;
if( i < 2){
console.log('inner',i);
i = i +1;
} else {
return ;
}
} else {
return ;
}
}
由于您希望在整个文件中使用i
,因此您可以全局声明它:
var i = 0;
for ( ; i < 2; i ++){
console.log('inner',i);
i = 100;
}
console.log('**************');
i =-1;
if( i < 2) {
console.log('inner',i);
i = 100;
i = i +1;
if( i < 2){
console.log('inner',i);
i = i +1;
if( i < 2){
console.log('inner',i);
i = i +1;
} else {
return ;
}
} else {
return ;
}
}
答案 2 :(得分:0)
上进行测试内
内部100(你定义了让i = 100,在for中使用第二次迭代,见4 /)
**************
内在
解决方案:
for (let i = 0; i < 2; i ++){
console.log('inner',i);
}
console.log('**************');
var i = -1; // Defines i with var instead of nothing, causing i = undefined
if(i < 2) {
console.log('inner',i);
i++; // Incrementation shortcut
if(i < 2){
console.log('inner',i);
i++;
if(i < 2){
console.log('inner',i);
i++;
}
}
}