从数组的javascript数组中获取未定义
Getting undefined from javascript array of arrays
这与我之前的问题有关,但略有不同,是一个全新的问题。。。我有一个数组,经过一些漂亮的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
和name
值undefined
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;
}
你用那些领先的0
来射自己的脚:series['001']
和series['1']
不一样。要么剪切parseInt
调用(强制用户键入"001"),要么删除前导0s:
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"
}
]
这:
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"
} ... ];
相关文章:
- 从json子数组获取数据
- 从javascript数组获取php的日期时间
- 从表中的 JSON 数组获取数据
- 每个表的2D数组获取坐标JTSL,JAVASCRIPT
- javascript从元素到数组获取文本
- 如何从数组获取链接以在youtube Iframe API中播放
- JSON 编码多维数组获取值
- 如何从两个 JSON 数组获取增量
- 通过单击按钮数组获取隐藏 html 元素值的当前数组
- 在 JavaScript 中从内部数组获取数据
- 从数组获取非重复索引在 0 时失败
- JavaScript 从对象中的数组获取数组
- 如何通过 ajax 将 php 数组作为 javascript 数组获取
- 快速从 2D 数组获取索引,无需迭代 jquery
- 从 Nodejs socketio 数组获取所有套接字 id
- 无法动态从 json 数组获取数据
- 如何在javascript中使用数组获取和设置html标签的值
- jQuery对象数组获取一个项作为jQuery对象
- 如何在不向输出数组获取空值的情况下拆分字符串
- 从输入到数组获取数据