javascript エラー「Uncaught TypeError: xxx.includes is not a function」の解決方法
- 作成日 2022.11.02
- 更新日 2022.11.03
- javascript
- javascript

javascriptで、エラー「Uncaught TypeError: xxx.includes is not a function」が発生した場合の原因と解決方法を記述してます。数値などに「includes」を使用した場合に発生します。「chrome」や「firefox」や「safari」の各ブラウザのエラーメッセージの画像もキャプチャしてます。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 107.0.5304.88
エラー内容
以下の、変数「num」に「includes」で指定した値が含まれているかを判定するコードで発生。
const num = 1234;
const result = num.includes('23');
console.log(result);
エラーメッセージ
Uncaught TypeError: num.includes is not a function
画像

firefox106の場合でも同じエラーが発生します。
Uncaught TypeError: str.contains is not a function
画像

safari15.5では、以下のエラーとなります。
TypeError: num.includes is not a function. (In 'num.includes('23')', 'num.includes' is undefined)
画像

原因
「includes」は、数値には使用できないため。
解決方法
一度、「toString()」で文字列に変換してから「includes」を使用します。
const num = 1234;
const result = num.toString().includes('23');
console.log(result); // true
もしくは、文字列であるかを判定してから使用します。
const num = 1234;
const result = typeof num === 'string' ? num.includes('23') : '文字列ではありません';
console.log(result); // 文字列ではありません
「includes」は、配列にも使用できるので必要であれば配列であるかも判定条件に加えます。
const num = 1234;
const result = typeof num === 'string' || Array.isArray(num) ? num.includes('23') : 'includesは使用できません';
console.log(result); // includesは使用できません
-
前の記事
Rust エラー「error[E0277]: cannot add a float to an integer」が発生した場合の対処法 2022.11.02
-
次の記事
AppleScript 繰り返しであるfor文を使用する 2022.11.02
コメントを書く