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

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

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

環境

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

エラー内容

以下の、文字列に対して「splice」を実行したコードにて発生。

const str = '123456';

const result = str.splice(2);

console.log( result );

エラーメッセージ

Uncaught TypeError: str.splice is not a function

画像

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

Uncaught TypeError: str.splice is not a function

画像

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

TypeError: str.splice is not a function. (In 'str.splice(2)', 'str.splice' is undefined)

画像

原因

「splice」は、文字列に使用できないため
※オブジェクトなどにも使用しても同じエラーが発生します。

const obj = {a: 1, b: 2, c: 3};

const result = obj.splice(2);
// Uncaught TypeError: obj.splice is not a function

console.log( result );

解決方法

一度「split(”)」で1文字づつ配列に分割してから使用する

const str = '123456';

const result = str.split('').splice(2);

console.log( result ); // ['3', '4', '5', '6']

console.log( result.toString() );
// 3,4,5,6

console.log( result.join("") );
// 345

または、配列であるかを判定して使用します。

const str = '123456';

const result = Array.isArray(str) ? str.splice(2) : '配列ではありません';

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