javascript エラー「Uncaught TypeError: xxx.charAt is not a function」の解決方法
- 作成日 2022.10.21
- javascript
- javascript
javascriptで、エラー「Uncaught TypeError: xxx.charAt is not a function」が発生した場合の原因と解決方法を記述してます。数値などに、文字列の指定された位置を取得することができる「charAt」を使用したときに発生します。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome106.0.5249.103
エラー内容
以下の、コードにて発生。
※その他に発生するパターンは後述してます。
const num = 1234;
const result = num.charAt(0);
エラーメッセージ
Uncaught TypeError: num.charAt is not a function
画像
firefox105の場合でも同じエラーが発生します。
Uncaught TypeError: num.charAt is not a function
画像
safari15.5では、以下のエラーとなります。
TypeError: num.charAt is not a function. (In 'num.charAt(0)', 'num.charAt' is undefined)
画像
原因
「charAt」は、文字列にのみ使用できるため、配列には使用できない
解決方法
一度、「map」で文字列に変換してから使用して「charAt」を実行するか、
const num = 1234;
const result = num.toString().charAt(0);
console.log(result); // 1
console.log(typeof result); // string
// 数値にする場合はNumberを使用する
console.log(typeof Number(result)); // number
文字列であるかを判定してから使用する。
const num = 1234;
const result = (typeof str === 'string') ? num.charAt(0) : '文字列ではありません';
console.log(result); // 文字列ではありません
配列に使用する場合は、要素を連結する「join」を使用して文字列に変換後に使用します。
const arr = ['abc','def','ghi'];
console.log(arr.join('')); // abcdefghi
const result = arr.join('').charAt(0);
console.log(result); // a
その他のパターン
文字列をインクリメント
文字列をインクリメントすると「数値」になるので、その後に「charAt」を使用するとエラーとなります。
let str = 'aaa';
let result = str.charAt(0);
console.log(result);
str++;
console.log(typeof str); // number
result = str.charAt(1); // Uncaught TypeError: str.charAt is not a function
-
前の記事
Dart エラー「Error: The argument type ‘List
‘ can’t be assigned to the parameter type ‘Iterable 2022.10.21‘.」が発生した場合の対処法 -
次の記事
javascript インチ(inch)からセンチメートル(cm)に変換する 2022.10.22
コメントを書く