【问题标题】:Javascript function return array undefined [duplicate]Javascript函数返回数组未定义[重复]
【发布时间】:2013-08-24 14:34:38
【问题描述】:

我有一个函数 loadTileSet()。此函数必须返回 arrTiles(图像数据数组),但函数返回的是 UNDEFINED。我正在使用 push 将数据放入数组..

function loadTileSet(){
        var canvas = document.getElementById('fakeCanvas');
        $('#fakeCanvas').hide();
        var ctx = $("canvas")[0].getContext('2d');
        var imgTileSet = new Image();
        imgTileSet.src = 'tileset.png';
        var imageTileNumWidth = 23;
        var imageTileNumHeight = 21;

        var arrTiles = [];

        imgTileSet.onload = function(){

            var imageWidth = imgTileSet.width;
            var imageHeight = imgTileSet.height;
            sndCanvasWidth = imageWidth/imageTileNumWidth;
            sndCanvasHeight = imageHeight/imageTileNumHeight;
            canvas.width = imageWidth;
            canvas.height = imageHeight;
            ctx.drawImage(imgTileSet,0,0,imageWidth,imageHeight);

            var i=0;
            var j=0;
            var t=0;
            for(i=0;i<imageWidth;i+=sndCanvasWidth){
                for(j=0;j<imageHeight;j+=sndCanvasHeight){
                    var myImageData = ctx.getImageData(j,i,sndCanvasWidth,sndCanvasHeight); 
                    arrTiles.push(myImageData);  
                }
            }
            return arrTiles;
        }
    }

在这里我尝试将数组放入另一个

var arrNew = loadTileSet();
console.log(arrNew[0]);

【问题讨论】:

  • 你是来自 onload 处理程序的returning,而不是来自loadTileSet 函数。
  • 问题是加载是异步完成的,你不能从函数返回imageDate。请参阅How to return the response from an AJAX call? 了解可能的解决方案。

标签: javascript arrays function


【解决方案1】:

Bergi 的评论已经说明了问题所在。这是一个异步进程,因此您需要将其作为一个进程来处理。总体思路是使用回调:

function loadTileSet(callback) {
    // ...

    imgTileSet.onload = function () {
        // instead of return, do this
        callback(arrTiles);
    };
}

loadTileSet(function (arrNew) {
    // now you can use arrNew
});

【讨论】:

    【解决方案2】:

    你的函数没有返回任何东西。此外,在您填充数组的位置,它被封装在 .onload 函数中。

    【讨论】:

      猜你喜欢
      • 2013-06-26
      • 2014-03-05
      • 1970-01-01
      • 2022-11-26
      • 2022-11-25
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      相关资源
      最近更新 更多