我有一个多维数组,其中存在一些值,我想检索[0][1]
或[1][1]
索引值。我得到未定义为数组,如果我尝试直接尝试获取数组值能够获取该值。
这是我想要实现的
我有一个选择下拉菜单,根据所选索引我需要从数组框中检索一条消息。例如,如果索引为 1,那么我必须获取[1][1]
数组索引值,如果它为零,那么[0][1]
数组索引值
这是我所做的小提琴。http://jsfiddle.net/hTQZ9/
我有一个多维数组,其中存在一些值,我想检索[0][1]
或[1][1]
索引值。我得到未定义为数组,如果我尝试直接尝试获取数组值能够获取该值。
这是我想要实现的
我有一个选择下拉菜单,根据所选索引我需要从数组框中检索一条消息。例如,如果索引为 1,那么我必须获取[1][1]
数组索引值,如果它为零,那么[0][1]
数组索引值
这是我所做的小提琴。http://jsfiddle.net/hTQZ9/
看到这个更新:http: //jsfiddle.net/hTQZ9/1/
var MessagesObj = {
testName: []
}
MessagesObj["testName"].push(["testName_custom_message_Label1val","Custom message for label 1"]);
MessagesObj["testName"].push(["testName_custom_message_Label2val","Custom message for label 2"]);
alert(MessagesObj["testName"][1][1]);
var classChk = $(".customCheckEnabled").get(0);
var getClassindex = classChk.selectedIndex;
var getVarName = classChk.id
var getCstMsgName = MessagesObj[getVarName];
alert(getCstMsgName);
var getMessage = getCstMsgName[getClassindex][1];
alert(getMessage);
getCstMsgName 是一个字符串,而不是一个数组。
一种方法是使用这个
$(document).ready(function () {
var testName_MessagesArray = new Array();
var cntr = 0;
testName_MessagesArray[cntr] = new Array("testName_custom_message_Label1val", "Custom message for label 1");
cntr++;
testName_MessagesArray[cntr] = new Array("testName_custom_message_Label2val", "Custom message for label 2");
cntr++;
alert(testName_MessagesArray[1][1]);
var classChk = $(".customCheckEnabled");
alert(classChk);
this.testName = testName_MessagesArray; //<-- set this with the name
var getClassindex = classChk.attr("selectedIndex");
alert(getClassindex);
var getVarName = classChk.attr("id");
alert(getVarName);
var getCstMsgName = this[getVarName]; //<-- reference it from this
alert(getCstMsgName);
var getMessage = getCstMsgName[getClassindex][1];
alert(getMessage);
});
如果testName_MessagesArray
在全局范围内,则window["testName_MessagesArray"]
可以引用它。您当前的示例是本地范围,因此不起作用。
你真的应该使用数组文字而不是,呃,cntr
s:
var testName_MessagesArray = [
["testName_custom_message_Label1val", "Custom message for label 1"],
["testName_custom_message_Label2val", "Custom message for label 2"]
];
然后,如果要从中检索值,请使用testName_MessagesArray[x][y]
.
你在做什么:
var classChk=$(".customCheckEnabled");
// this is a jQuery element, alerted as [object Object]
var getClassindex=classChk.attr("selectedIndex");
// this is 0 or 1
var getVarName=classChk.attr("id");
// this will be the id of the first selected element, a string
var getCstMsgName=getVarName+"_MessagesArray".toString();
// this will create a string, from the "getVarName"-string and your string-literal-toString
var getMessage=getCstMsgName[getClassindex][1];
// as "getCstMsgName" is a string - not the twodimensional array,
// getCstMsgName[getClassindex] returns the character at the selected index (as a string)
// and getCstMsgName[getClassindex][1] results in the second character of the one-character-string - undefined