javascript エラー「Uncaught TypeError: Cannot read properties of undefined (reading ‘xxx’)」の解決方法
- 2022.05.10
- javascript
- javascript

javascriptで、エラー「Uncaught TypeError: Cannot read properties of undefined (reading ‘xxx’)」が発生した場合の原因と解決方法を記述してます。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 98.0.4758.102
エラー内容
以下のコードを実行時に発生
const arr = [0, 1, 2];
console.log(arr[3].toString());
エラーメッセージ
console.html:40 Uncaught TypeError: Cannot read properties of undefined (reading 'toString')
画像

firefox(バージョン97)では、下記のエラーとなります。
Uncaught TypeError: arr[3] is undefined
画像

原因
存在しない配列のインデックス番号を指定しているため。
解決方法
存在するものを指定する
const arr = [0, 1, 2];
console.log(arr[2].toString());
実行結果

-
前の記事
Linux コマンドでユーザーidを確認する 2022.05.09
-
次の記事
java splitで複数の区切り文字を使用する 2022.05.10
コメントを書く