我尝试将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
关于javascript - 链接reduce() 和map() Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50635911/