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

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

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

環境

  • OS windows11 pro 64bit
  • ブラウザ chrome 108.0.5359.99

エラー内容

以下の、「オブジェクト」のプロパティ追加に「push」を使用したコードで発生。

const obj = {
  name: 'itiro',
  age: 25,
};

obj.push({tel: '0123456'});

エラーメッセージ

Uncaught TypeError: obj.push is not a function

画像

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

Uncaught TypeError: obj.push is not a function

画像

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

TypeError: obj.push is not a function. (In 'obj.push({tel: '0123456'})', 'obj.push' is undefined)

画像

原因

「push」は配列には使用できるがオブジェクトには使用できないため

const obj = [{
  name: 'itiro',
  age: 25,
}];

obj.push({tel: '0123456'});

console.log( obj );
// [{name: 'itiro', age: 25},{tel: '0123456'}]

解決方法

「オブジェクト」にプロパティを追加する場合は、以下のようにします。

const obj = {
  name: 'itiro',
  age: 25,
};

obj.tel ='0123456';

console.log( obj );
// {name: 'itiro', age: 25, tel: '0123456'}

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

const obj = {
  name: 'itiro',
  age: 25,
};

const result = Array.isArray(obj) ? obj.push({tel: '0123456'}) : '配列ではありません';

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