无法从多维数组中检索值

时间:2012-05-24 11:53:07

标签: javascript jquery multidimensional-array

我有一个多维数组,其中存在一些值i  想要检索[0][1][1][1]索引值。我正进入(状态  undefined as array,如果我试图直接尝试获取数组值  能够获得价值。

这就是我想要实现的目标

我有一个选择下拉菜单,根据所选索引我  需要从数组框中检索消息。比方说索引是  1然后我必须获得[1][1]数组索引值,如果它是零,那么[0][1]  数组索引值

这是我所做的小提琴。 http://jsfiddle.net/hTQZ9/

3 个答案:

答案 0 :(得分:1)

请参阅此更新: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);

答案 1 :(得分:0)

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"]来引用它。您当前的示例是本地范围,因此无法正常工作。

答案 2 :(得分:0)

你应该使用数组文字而不是呃,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
相关问题