从函数返回数组

时间:2012-08-21 16:46:11

标签: javascript arrays function

- 由Elliot B解决。谢谢! 也可以考虑其他修改。

结果如下。谢谢大家,快速回答! http://dl.dropbox.com/u/18785762/Rust/index.html

我正在用javascript编写游戏,并且我希望将用于匹配块ID的文件保存到来自地图编译器的单独.js文件中的文件,以便我可以轻松编辑。但是,ID存储在一个数组中,我似乎无法正确使用返回函数。有什么帮助吗?

drawmap.js:

function drawmap() {

    var images = BlockID();

    var level = [
    "ssssssssssssssssssssss",
    "sgggggggggCCCCCdddddss",
    "ssssssssss     sssssss"
    ];

    var top = 100;
    var left = 100;
    var mytop = top;
    var myleft = left;
    for (y=0; y<level.length; ++y) {
        var row = level[y];
        for (x=0; x < row.length; ++x) {
            var c = row.charAt(x);
            if(c != ' ') {
                img_create(images[c], mytop, myleft);
            }
            mytop += 13;
            myleft += 27;
        }
        mytop = top + (y+1)*13;
        myleft = left - (y+1)*27;
    }
}

mapread.js:

function BlockID() {
    var IDs = new Array();
        images['s'] = "Images/Block_01.png";
        images['g'] = "Images/Block_02.png";
        images['C'] = "Images/Block_03.png";
        images['d'] = "Images/Block_04.png";
    return IDs;
}

3 个答案:

答案 0 :(得分:40)

至少,改变一下:

function BlockID() {
    var IDs = new Array();
        images['s'] = "Images/Block_01.png";
        images['g'] = "Images/Block_02.png";
        images['C'] = "Images/Block_03.png";
        images['d'] = "Images/Block_04.png";
    return IDs;
}

对此:

function BlockID() {
    var IDs = new Object();
        IDs['s'] = "Images/Block_01.png";
        IDs['g'] = "Images/Block_02.png";
        IDs['C'] = "Images/Block_03.png";
        IDs['d'] = "Images/Block_04.png";
    return IDs;
}

有几点需要指出。 第一个images未在原始函数中定义,因此为其指定属性值将引发错误。我们通过将images更改为IDs来更正此问题。 第二次,您想要返回Object,而不是Array。可以为对象分配类似于关联数组或散列的属性值 - 数组不能。因此,我们将var IDs = new Array();的声明更改为var IDs = new Object();

在这些更改之后,您的代码运行正常,但可以进一步简化。您可以使用简写表示法(即,对象文字属性值简写)来创建对象并立即返回:

function BlockID() {
    return {
            "s":"Images/Block_01.png"
            ,"g":"Images/Block_02.png"
            ,"C":"Images/Block_03.png"
            ,"d":"Images/Block_04.png"
    };
}

答案 1 :(得分:12)

您的BlockID函数使用未定义的变量images,这将导致错误。此外,您不应在此处使用Array - JavaScripts键值映射是普通对象:

function BlockID() {
    return {
        "s": "Images/Block_01.png",
        "g": "Images/Block_02.png",
        "C": "Images/Block_03.png",
        "d": "Images/Block_04.png"
    };
}

答案 2 :(得分:7)

整洁:

function BlockID() {
  return {
    "s":"Images/Block_01.png",
    "g":"Images/Block_02.png",
    "C":"Images/Block_03.png",
    "d":"Images/Block_04.png"
   }
}

或只是

var images = {
  "s":"Images/Block_01.png",
  "g":"Images/Block_02.png",
  "C":"Images/Block_03.png",
  "d":"Images/Block_04.png"
}