For 循环 ReferenceError: ‘i’ is not defined in JS

For 循环 ReferenceError: ‘i’ is not defined in JS

For loop ReferenceError: ‘i’ is not defined in JS

“ReferenceError: i is not defined”错误发生在我们忘记使用
let语句在for循环中定义索引变量时。

要解决该错误,请使用let语句在循环中声明变量。

referenceeeror i 未定义

这是错误是如何引起的示例。

索引.js
const arr = ['a', 'b', 'c']; // ⛔️ ReferenceError: i is not defined for (i = 0; i < arr.length; i++) { console.log(arr[i]); }

请注意,我们没有在循环中声明i变量。for

为了解决这个错误,我们不得不在for
循环中使用
let声明变量
的语句。

索引.js
const arr = ['a', 'b', 'c']; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); // 👉️ a, b, c }

We used the let statement to declare the i variable in the loop.

The let statement allows us to declare a block-scoped variable (one that’s only available in the for loop).

Variables declared using let can also be reassigned, as opposed to variables
declared using const.

Don’t try to declare the i variable in a loop using the const statement.

index.js
const arr = ['a', 'b', 'c']; // ⛔️ Assignment to constant variable for (const i = 0; i < arr.length; i++) { console.log(arr[i]); // 👉️ a, b, c }

When we try to reassign the value of the i variable on the second iteration,
we get the “Assignment to constant variable” error because constants cannot
be reassigned.

In older code snippets you might see the var statement used to declare the
variable in a loop.

index.js
const arr = ['a', 'b', 'c']; for (var i = 0; i < arr.length; i++) { console.log(arr[i]); // 👉️ a, b, c }

This also works but is not a good practice because the variable we declared
using var is not block-scoped. We can access it outside of the for loop.

index.js
const arr = ['a', 'b', 'c']; for (var i = 0; i < arr.length; i++) { console.log(arr[i]); // 👉️ a, b, c } console.log(i); // 👉️ 3

Polluting the upper scope for no reason is a bad practice, so you should be
using the let keyword to declare variables in a for loop.

You can also use the Array.forEach() method if you need to iterate over an
array with access to the current index.

index.js
const arr = ['a', 'b', 'c']; arr.forEach((element, index) => { console.log(element, index); // 👉️ a 0, b 1, c 2 });

The function we passed to the
Array.forEach
method gets called with each element in the array and its index.

If you don’t need access to the index of the current iteration, you can also use
a for...of loop.

index.js
const arr = ['a', 'b', 'c']; for (const element of arr) { console.log(element); // 👉️ a b c }

for…of
语句用于循环遍历可迭代对象,如数组、
字符串
Map
SetNodeList对象generators

结论

“ReferenceError: i is not defined”错误发生在我们忘记使用
let语句在for循环中定义索引变量时。

要解决该错误,请使用let语句在循环中声明变量。