You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript链式调用reduce()与map()报错:map不是函数的排查与解决

嘿,我来帮你拆解下这个问题以及解决办法~

错误原因解析

你碰到的TypeError: boxarts.reduce(...).map is not a function其实很好理解:
reduce()方法的作用是把数组缩减为单个值——在你的代码里,它最终返回的是尺寸最大的那个box art对象(比如{ width: 425, height: 150, url: "xxx" }),而不是一个数组。但map()是数组专属的方法,只能在数组实例上调用,直接在单个对象上用map自然会抛出类型错误。

解决方案

要实现“得到包含最大尺寸box art的url的对象数组”这个需求,只需要把reduce返回的单个对象包裹成数组,就能正常调用map了。修改后的代码如下:

const boxarts = [
  { width: 600, height: 700, url: "http://cdn-0.nflximg.com/images/2891/Fracture600.jpg" },
  { width: 500, height: 500, url: "http://cdn-0.nflximg.com/images/2891/Fracture500.jpg" },
  { width: 425, height: 150, url: "http://cdn-0.nflximg.com/images/2891/Fracture425.jpg" },
  { width: 200, height: 200, url: "http://cdn-0.nflximg.com/images/2891/Fracture200.jpg" }
]

let newReduce = [boxarts.reduce(function(acc, currentValue) {
  if (acc.width * acc.height > currentValue.width * currentValue.height) {
    return acc
  } else {
    return currentValue
  }
})].map(function(item) {
  return { url: item.url}
})

console.log(newReduce)

核心修改说明

  • 用方括号[]把boxarts.reduce(...)的结果包裹起来,将单个对象转化为只有一个元素的数组
  • 此时数组可以正常调用map(),把原对象转换为只包含url属性的新对象,最终得到你想要的结果数组

额外小技巧

如果你其实只需要获取url字符串(而不是对象数组),完全可以省去map,直接取reduce结果的url属性:

const largestBoxart = boxarts.reduce((acc, curr) => 
  acc.width * acc.height > curr.width * curr.height ? acc : curr
);
console.log(largestBoxart.url); // 直接输出目标url字符串

内容的提问来源于stack exchange,提问作者John John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:55:36