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

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

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

環境

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

エラー内容

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

const str = '123456';

const sum = str.reduce( function (accumulator, currentValue) {
  return accumulator + currentValue
})

エラーメッセージ

Uncaught TypeError: str.reduce is not a function

画像

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

Uncaught TypeError: str.reduce is not a function

画像

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

TypeError: str.reduce is not a function. (In 'str.reduce( function (accumulator, currentValue) {
  return accumulator + currentValue
})', 'str.reduce' is undefined)

画像

原因

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

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

const sum = obj.reduce( function (accumulator, currentValue) {
  return accumulator + currentValue
})
// Uncaught TypeError: obj.reduce is not a function

解決方法

合計を求めるのであれば、一度「split(”)」で1文字づつ配列に分割してから使用する

const str = '123456';

console.log(str.split(''));
// ['1', '2', '3', '4', '5', '6']

const sum = str.split('').reduce( function (accumulator, currentValue) {
  return Number(accumulator) + Number(currentValue)
})

console.log( sum );
// 21

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

const str = '123456';

const sum =  Array.isArray(str) ? str.split('').reduce( function (accumulator, currentValue) {
  return Number(accumulator) + Number(currentValue)
}) : '配列ではありません';

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