javascript エラー「Uncaught SyntaxError: for-in loop variable declaration may not have an initializer.」の解決方法
- 2022.06.03
- javascript
- javascript

javascriptで、エラー「Uncaught SyntaxError: for-in loop variable declaration may not have an initializer.」が発生した場合の原因と解決方法を記述してます。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 102.0.5005.63
エラー内容
以下のコードで発生。
'use strict'
let obj = {a: 1, b: 2, c: 3 };
for (let i = 0 in obj) {
console.log(obj[i]);
}
エラーメッセージ
※厳格モードの「use strict」のみ発生します。
Uncaught SyntaxError: for-in loop variable declaration may not have an initializer.
画像

firefox(バージョン97)では、以下のエラーとなります。
Uncaught SyntaxError: a lexical declaration in the head of a for-in loop can't have an initializer
画像

原因
for in に初期値は必要ないため
解決方法
初期値を設定しない
'use strict'
let obj = {a: 1, b: 2, c: 3 };
for (let i in obj) {
console.log(obj[i]);
}
実行結果

-
前の記事
java コメントアウトする 2022.06.02
-
次の記事
VBA 関数が入力されているかを判定する 2022.06.03
コメントを書く