Dav*_*ude 0 javascript jquery multidimensional-array
我试图将一些数据传递给一个函数,该函数使用这些参数作为多维数组的标识符,然后返回硬编码到该数组的值.我不确定我做错了什么,但有些事情正在破裂.
在分配任何数组值之前,我可以获得一个alert()来弹出,但它似乎在那时就死了.任何帮助表示赞赏.
// Get Column A's number
var a1 = Number($('#p-a').attr("numb"));
// Get Column B's number
var b1 = Number($('#p-b').attr("numb"));
// Get status for column A
var a_status = $('#p-a').attr("status");
// Get status for column A
var b_status = $('#p-b').attr("status");
// If same, status="s" else, status="i"
var status = "";
if(a_status == b_status) { status = "s"; }else{ status = "o"; }
// Get the value of the numbers + status
var a = this_function(a1, b1, status, "2");
// Update the status div
$('#status').html(a);
function this_function(a1, a2, s, p)
{
this_array = array();
this_array['1']['1']['1']['1'] = "10";
this_array['1']['1']['1']['2'] = "20";
this_array['1']['2']['1']['1'] = "40";
this_array['1']['2']['1']['2'] = "60";
//
return this_array[a1][a2][s][p];
}
Run Code Online (Sandbox Code Playgroud)
你不能像这样初始化数组.每个级别都需要单独初始化.因为你没有数字键,我会使用一个对象:
var this_array = {
'1': {
'1': {
'o': {
'1': "10",
'2': "20"
}
},
'2': {
'o': {
'1': "40",
'2': "60"
}
}
}
};
Run Code Online (Sandbox Code Playgroud)
如果密钥不存在,您还必须定义会发生什么.例如,如果status是,'s'那么你将得到一个错误.
该if声明可以通过编写短条件运算符:
var status = (a_status == b_status) ? 's' : 'o';
Run Code Online (Sandbox Code Playgroud)
更新:如果你真的想要一个数值数组,只要键只是数字,你可以像这样创建数组:
var this_array = [
[], // this_array[0]
[ // this_array[1]
[], // this_array[1][0]
[ // this_array[1][1]
[], // this_array[1][1][0]
[null, 10, 20] // this_array[1][1][1][...]
],
[ // this_array[1][2]
[], // this_array[1][2][0]
[null, 40, 60] // this_array[1][2][1][...]
]
]
];
Run Code Online (Sandbox Code Playgroud)
你看,如果你没有开始你的索引与0结构变得相当混乱.