javascript - 链接reduce() 和map() Javascript

标签 javascript

我尝试将reduce() 与map() 结合起来,将多个盒子艺术对象减少为单个值:最大盒子艺术的url。
它给了我以下错误:

VM272:20 Uncaught TypeError: boxarts.reduce(...).map is not a function at <anonymous>:20:4

不知道到底出了什么问题

const boxarts = [
  { width: 200, height: 200, url: "http://cdn-0.nflximg.com/images/2891/Fracture200.jpg" },
  { width: 150, height: 200, url: "http://cdn-0.nflximg.com/images/2891/Fracture150.jpg" },
  { width: 300, height: 200, url: "http://cdn-0.nflximg.com/images/2891/Fracture300.jpg" },
  { width: 425, height: 150, url: "http://cdn-0.nflximg.com/images/2891/Fracture425.jpg" }
]
let newReduce = boxarts.reduce(function(accumulator, currentValue) {
  if (accumulator.width * accumulator.height > currentValue.width * currentValue.height) {
    return accumulator
  } else {
    return currentValue
  }
}).map(function(item) {
  return item.url
})

console.log(newReduce)

最初问题的解决方案。它将链接作为对象数组返回。

    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)

最佳答案

const boxarts = [
        { width: 200, height: 200, url: "http://cdn-0.nflximg.com/images/2891/Fracture200.jpg" },
        { width: 150, height: 200, url: "http://cdn-0.nflximg.com/images/2891/Fracture150.jpg" },
        { width: 300, height: 200, url: "http://cdn-0.nflximg.com/images/2891/Fracture300.jpg" },
        { width: 425, height: 150, url: "http://cdn-0.nflximg.com/images/2891/Fracture425.jpg" }
    ]

    let newReduce = boxarts.reduce(function (accumulator, currentValue) {

        if (accumulator.width * accumulator.height > currentValue.width * currentValue.height) {
            return accumulator
        } else {
            return currentValue
        }
    })

    console.log(newReduce.url)

从您的映射函数来看,您似乎正在尝试获取url,问题是newReduce是一个对象,并且没有map函数。只需使用 newReduce.url

即可轻松获取 url

关于javascript - 链接reduce() 和map() Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50635911/

相关文章:

javascript - 测验 - if 语句

javascript - 动态 CRM : JavaScript GET request is not retrieving records using Web. API

javascript - Firefox 附加组件 SDK 1.16 的 Web 控制台中的 console.log

javascript - react 等待服务器响应

javascript - 函数内的警报和函数调用发生故障

javascript - 禁用 Mozilla Firefox 存储 javascript

javascript - vue - $emit 与更新父数据的引用

javascript - 嵌套函数丢失变量引用

javascript - 如何在Javascript中实现正则表达式的正 "lookbehind"

Javascript 函数参数评估