Javascript数组为空但指定了值

时间:2018-06-05 04:57:55

标签: javascript



var images = ['https://www.vsss.co.in/Admin/uploads/360756/JEWEL_HEXAGON_BIG.jpg', 'https://www.vsss.co.in/Admin/uploads/536145/JEWEL_MUNCHY_LUNCH_BOX.jpg', 'https://www.vsss.co.in/Admin/uploads/659266/BIG_BOSS_NO_3_LUNCH_BOX.jpg', 'https://www.vsss.co.in/Admin/uploads/314773/JEWEL_FLIP_LOCK_BIG_LUNCH_BOX.jpg', 'https://www.vsss.co.in/Admin/uploads/547563/JEWEL_RELISH_BIG_LUNCH_BOX.jpg', 'https://www.vsss.co.in/Admin/uploads/149811/JEWEL_BOB_DORA_LUNCH_BOX.jpg']
var content = [];
images.forEach(function(element, index) {
    let image = element;
    let image_name = image.substring(image.lastIndexOf('/') + 1).split('.');
    let extension = image_name[1];
    convertToDataURLviaCanvas(element, "image/" + extension).then(base64 => {
        content.push({
            image: base64,
            alignment: 'center',
            pageBreak: 'after'
        })
    })
})
console.log(content);
function convertToDataURLviaCanvas(url, outputFormat) {
    return new Promise((resolve, reject) => {
        let img = new Image();
        img.crossOrigin = 'anonymous';
        img.onload = () => {
            let canvas = document.createElement('CANVAS'),
                ctx = canvas.getContext('2d'),
                dataURL;
            canvas.height = img.height;
            canvas.width = img.width;
            ctx.drawImage(img, 0, 0);
            dataURL = canvas.toDataURL(outputFormat);
            resolve(dataURL);
            canvas = null;
        };
        img.src = url;
    });
}




我的问题是我在console.log(内容);然后内容是空的。任何人都可以告诉我为什么内容是空的,我可以解决这个问题所以我可以访问内容数组。

0 个答案:

没有答案