如何使用变量构建数组名称?

时间:2014-01-08 18:00:54

标签: jquery arrays function

我有几组数组。每组都以相同的单词开头:

var firstarrayquestions = ["", "", ""];
var firstarrayanswer1 = ["", "", ""];
var firstarrayanswer2 = ["", "", ""];

var secondarrayquestions = ["", "", ""];
var secondarrayanswer1 = ["", "", ""];
var secondarrayanswer2 = ["", "", ""];

(...等...)

这可能是一个有明显解决方案的问题,但如果我想要一个处理每个数组显示问题和答案的函数,我该怎么编码呢?像这样:

function handleQuestion(myStr) {
    var randomstart = 0; //just for example
    $('#question').text(myStr + arrayquestions[randomstart]);
    $('#q1').text(myStr + arrayanswer1[randomstart]);
    $('#q2').text(myStr + arrayanswer2[randomstart]);
}

handleQuestion('first');

非常感谢!

1 个答案:

答案 0 :(得分:2)

如果您知道范围,可以使用括号表示法,例如

function handleQuestion(myStr) {
    var randomstart = 0; //just for example
    $('#question').text(window[myStr + 'arrayquestions'][randomstart]);
    $('#q1').text(window[myStr + 'arrayquestions'][randomstart]);
    $('#q2').text(window[myStr + 'arrayquestions'][randomstart]);
}

handleQuestion('first');

但为什么不使用对象

var questions = {
    first: {
         questions : ["", "", ""],
         answer1   : ["", "", ""],
         answer2   : ["", "", ""]
    },
    second: {
         ...etc
    }
}

你可以这样访问它们:

function handleQuestion(myStr) {
    var randomstart = 0; //just for example
    var obj = questions[myStr];

    $('#question').text(obj.questions[randomstart]);
    $('#q1').text(obj.answer1[randomstart]);
    $('#q2').text(obj.answer2[randomstart]);
}

handleQuestion('first');