【发布时间】:2019-05-06 11:17:23
【问题描述】:
我在遍历包含图像的对象数组时遇到了困难。正如我下面的代码显示控制台中的数组看起来有点空但是当我在控制台中打开它时,我看到所有这些对象也带有迭代编号。我无法通过谷歌搜索并指出如何将其转换为正确的工作数组以进行 for in 循环并在 Vue.js 中迭代它。 我附上 cmets 比我的描述更多的代码。
const frameImage = [
{
url: 'http://www.realmadryt.pl/fotki/_up/newsy/lukamodric_165.png'
},
{
url: 'http://www.realmadryt.pl/fotki/_up/newsy/florentinoperez_11.jpg'
},
{
url: 'http://www.realmadryt.pl/fotki/_up/newsy/ramosbarkinsta1.jpg'
},
{
url: 'http://www.realmadryt.pl/fotki/_up/newsy/lukamodric_165.png'
},
{
url: 'http://www.realmadryt.pl/fotki/_up/newsy/florentinoperez_11.jpg'
},
{
url: 'http://www.realmadryt.pl/fotki/_up/newsy/ramosbarkinsta1.jpg'
},
];
let createdImages = [];
frameImage.forEach(item => {
const image = new Image();
image.src = item.url;
image.onload = () => {
// set image only when it is loaded
createdImages.push({
image,
width: image.width,
height: image.height,
x: 0,
y: 0,
draggable: true
});
};
});
console.log(createdImages)
// nothing happens
createdImages.forEach(item => {
console.log(item)
});
//also nothing happens
for(img in createdImages) {
console.log(img);
}
//length is actually 0?
console.log(createdImages.length)
还有jsFiddle:LINK
【问题讨论】:
-
什么都没有发生,因为您在
onload触发并填充它之前循环了createdImages。 -
哦,没想到是异步操作。谢谢!
标签: javascript arrays image-processing vue.js