Javascript:从缓存加载图像时数组未定义

时间:2017-01-06 10:16:35

标签: javascript arrays image

我一直在测试JavaScript中的大量代码,以便更轻松地将图像序列加载到网页上(遵循DRY规则)。正确加载所有32个图像(我可以在按F12时在Web开发人员工具包中查看它们),但是当我尝试验证图像已添加到数组缓存时,它返回undefined(暗示没有添加任何图像)。

JavaScript的:

var cache = [];

function imgList(base,firstNum,lastNum) {

    var img;
    for(var i = firstNum;i <= lastNum; i++) {
        img = new Image();

        if(i <=9){ var EXT = '000'}
        else if(i <= 99){var EXT = '00'}
        else if(i <= 999){var EXT = '0'}
        else{var EXT = ''}

        img.src = base + "." + EXT + i + ".jpg";
        cache.push(img);
    }

}

imgList("Scene%201/scene%201",1,32);

alert(document.write(cache.length));

1 个答案:

答案 0 :(得分:0)

var cache = [];

alert(cache.length);

function imgList(base,firstNum,lastNum) {

    var img;
    for(var i = firstNum;i <= lastNum; i++) {
        img = new Image();

        if(i <=9){ var EXT = '000'}
        else if(i <= 99){var EXT = '00'}
        else if(i <= 999){var EXT = '0'}
        else{var EXT = ''}

        img.src = base + "." + EXT + i + ".jpg";
        cache.push(img);
    }

}

imgList("Scene%201/scene%201",1,32);

alert(cache.length);

工作得很好......

JSFiddle