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

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

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

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome106.0.5249.103

エラー内容

以下の、数値に対して文字列を結合するコードにて発生。

const num = 123;
const str = '456';

num.concat(str);

エラーメッセージ

Uncaught TypeError: num.concat is not a function

画像

firefox105の場合でも同じエラーが発生します。

Uncaught TypeError: num.concat is not a function

画像

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

TypeError: num.concat is not a function. (In 'num.concat(str)', 'num.concat' is undefined)

画像

原因

「concat」は、「String.prototype.concat()」か「Array.prototype.concat()」なため数値には使用できない
※オブジェクトなどにも使用できません。

const obj = {name: 'mebee'};
const str = '456';

obj.concat(str);
// Uncaught TypeError: obj.concat is not a function

解決方法

一度、「toString()」で文字列に変換してから使用して「concat」を実行するか、

const num = 123;
const str = '456';

console.log( num.toString().concat(str) );
// 123456

console.log( typeof num.toString().concat(str) );
// string

// 数値に変換する場合はNumberを使用
console.log( Number(num.toString().concat(str)) );
// 123456

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

const num = 123;
const str = '456';

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

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

配列であるかを判定する場合は「Array.isArray」を使用します。

const arr = ['aaa'];
const str = 'bbb';

const result1 = Array.isArray(arr) ? arr.concat(str) : '配列ではありません';

console.log(result1); // ['aaa', 'bbb']

const result2 = Array.isArray(str) ? arr.concat(str) : '配列ではありません';

console.log(result2); // 配列ではありません