javascript エラー「Uncaught TypeError: xxx.startsWith is not a function」の解決方法

javascript エラー「Uncaught TypeError: xxx.startsWith is not a function」の解決方法

javascriptで、エラー「Uncaught TypeError: xxx.startsWith is not a function」が発生した場合の原因と解決方法を記述してます。文字列以外に「startsWith」を使用した場合に発生します。「chrome」や「firefox」や「safari」の各ブラウザのエラーメッセージの画像もキャプチャしてます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 107.0.5304.88

エラー内容

以下の、数値に対して指定した値で始まるかを判定するコードで発生。

const num = 10000;

const result = num.startsWith('1');

console.log( result );

エラーメッセージ

Uncaught TypeError: num.startsWith is not a function

画像

firefox106の場合では、以下のエラーが発生します。

Uncaught TypeError: num.startsWith is not a function

画像

safari15.5では、以下のエラーとなります。

TypeError: num.startsWith is not a function. (In 'num.startsWith('1')', 'num.startsWith' is undefined)

画像

原因

数値に対して「startsWith」を使用しているため。「startsWith」は文字列に使用します。

const result = 'abc'.startsWith('a');

console.log(result); // true

解決方法

「文字列」に変換して使用するか、

const num = 10000;

const result = num.toString().startsWith('1');

console.log( result ); // true

文字列であるかを判定してから使用する

const num = 10000;

const result = typeof str === 'string' ? num.startsWith('1') : '文字列ではありません';

console.log( result ); // 文字列ではありません