使用Actionscript 3中的变量引用数组的元素

时间:2015-03-30 05:30:03

标签: arrays actionscript-3

我有一堆数组(Q001,Q002,Q003 ......)。每个数组都是一个问题加上4个可能的答案。我想随机选择要显示的问题。所以我随机地为变量selectedQuestion分配一个数组名称。然后我尝试将该数组的第一个元素写入文本框,如下所示: txt.Question.text = [chosenQuestion] [0];

例如,如果所选问题是Q001,那么它将Q001放在文本框中。但我真的希望在文本框中是Q001数组的第一个元素。

1 个答案:

答案 0 :(得分:1)

假设您有3个问题数组,那么为了得到问题,您可以这样做:

var question_01:Array = ['question 01', 'answer 01', 'answer 02', 'answer 03', 'answer 04'];
var question_02:Array = ['question 02', 'answer 01', 'answer 02', 'answer 03', 'answer 04'];
var question_03:Array = ['question 03', 'answer 01', 'answer 02', 'answer 03', 'answer 04'];

var selected_question:int = Math.ceil(Math.random() * 3);   // gives : 1, 2 or 3

trace(this['question_0' + selected_question][0]);   // gives : question 01, for example

您还可以将问题数组放入如下数组中:

var questions:Array = [
    ['question 01', 'answer 011', 'answer 02', 'answer 03', 'answer 04'],
    ['question 02', 'answer 012', 'answer 02', 'answer 03', 'answer 04'],
    ['question 03', 'answer 013', 'answer 02', 'answer 03', 'answer 04']
];
selected_question = Math.floor(Math.random() * 3);  // gives : 0, 1 or 2

trace(questions[selected_question][0]); // gives : question 02, for example

希望可以提供帮助。