// Returns a promise that resolves with the average dimensions of all the passed in images
// Ignores any images that fail to load
function loadImages(images) {
// Complete the body of this function
// so that the tests below pass.
}
我尝试了很多不同的方法,但是仍然无法正常工作。有人可以帮忙吗?我尝试过map(),reduce()。但是总是得到NaN。
答案 0 :(得分:0)
我不会尝试通过您的测试,但这是您想要做的一个粗略示例:
loadImage
,以“保证”图像的加载。如果图像错误resolve(null)
,那么您可以在计算平均值时稍后将其过滤掉。Promise.all
以确保所有图像都已加载。Array.filter
过滤掉null
个错误图像。Array.reduce
对尺寸进行平均。
const loadImage = url => {
const image = new Image()
image.src = url
return new Promise(res => {
if (image.complete) return res(image)
image.onload = () => res(image)
image.onerror = () => res(null)
})
}
const getAverageDimsOfImageURLs = imageURLs => {
return Promise.all(imageURLs.map(loadImage))
.then(images => {
// filter out errored images
images = images.filter(image => image)
return images.reduce((acc, image, index) => {
acc.width += image.width
acc.height += image.height
if (index === images.length - 1) {
acc.width = acc.width / images.length
acc.height = acc.height / images.length
}
return acc
}, {
width: 0,
height: 0
})
})
}
const imageURLs = [
'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
'http://tineye.com/images/widgets/mona.jpg',
'http://nonexis2tent.com/images/widgets/mona.jpg' // Bad URL.
]
getAverageDimsOfImageURLs(imageURLs)
.then(console.log)
.catch(console.error)