0

这与我之前的问题有关,但是它略有不同,并且是一个全新的问题...我有一个数组,经过一些不错的 PHP 之后,它看起来像这样:

var series = {
    "001":{
        "game":"Portal 2",
        "name":"Portal 2"
    },
    "002":{
        "game":"Minecraft",
        "name":"241"
    },
    "003":{
        "game":"Minecraft",
        "name":"HackMine"
    },
    "004":{
        "game":"Mass Effect 3",
        "name":"Mass Effect 3"
    },
    "005":{
        "game":"League of Legends",
        "name":"League of Legends"
    },
    "006":{
        "game":"Half Life 2",
        "name":"The Hidden: Source"
    },
    "007":{
        "game":"Skyrim",
        "name":"Modded Skyrim"
    }
}

这一点填充得很好......现在我的问题是当这个函数被调用时,它总是给出game并且nameundefined

function seriesIdOnBlur()
{       

    var id = parseInt(document.getElementById("series_id").value);

    if (series[id] == null)
    {
        var message = "The Series ID you input was invalid";
    }
    else
    {
        var seriesId = series[id];

        var game = seriesId['game'];
        var name = seriesId['name'];
        var message = "You've inputted the id for the game: " + game + " for the series: " + name;
    }

    document.getElementById("series_id_check").innerHTML = message;
}
4

2 回答 2

6

你用那些领先0的 ​​s:series['001']series['1']. 要么中断parseInt通话(强制用户输入“001”),要么删除前导 0:

var series = {
    "1":{
        "game":"Portal 2",
        "name":"Portal 2"
    },
    ...
    "7":{
        "game":"Skyrim",
        "name":"Modded Skyrim"
    }
}

或使用数组:

var series = [
    {
        "game":"Portal 2",
        "name":"Portal 2"
    },
    ...
    {
        "game":"Skyrim",
        "name":"Modded Skyrim"
    }
]
于 2013-08-07T23:01:49.797 回答
1

这:

series = {
    "001":{
        "game":"Portal 2",
        "name":"Portal 2"
    },
    "002":{
        "game":"Minecraft",
        "name":"241"
    } ... };

是一个对象文字,所以你有 Object of Objects 而不是 Array of Arrays 如你所说。

您将需要对象数组才能使您的代码正常工作:

series = [
    {
        "game":"Portal 2",
        "name":"Portal 2"
    },
    {
        "game":"Minecraft",
        "name":"241"
    } ... ];
于 2013-08-07T23:05:08.140 回答