我试图将一些数据传递给一个函数,该函数使用这些参数作为多维数组的标识符,然后返回硬编码到该数组的值。我不确定我做错了什么,但有些东西正在破坏。
在分配任何数组值之前,我可以弹出一个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];
}
最佳答案
你不能像这样初始化数组。每个级别都需要单独初始化。由于您没有只有数字键,所以我会使用 object相反:
var this_array = {
'1': {
'1': {
'o': {
'1': "10",
'2': "20"
}
},
'2': {
'o': {
'1': "40",
'2': "60"
}
}
}
};
您还必须定义如果 key 不存在会发生什么情况。例如。目前,如果 status
是 's'
那么您将收到错误。
使用 conditional operator 可以将 if
语句写得更短。 :
var status = (a_status == b_status) ? 's' : 'o';
<小时/>
更新:如果您确实想要一个数字数组,只要键只是数字,您可以像这样创建数组:
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][...]
]
]
];
你看,如果你不以 0
开始索引,结构就会变得非常困惑。
关于Javascript函数和数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4741843/