Javascript-在列表中选择元素

Javascript-在列表中选择元素,javascript,html,arrays,Javascript,Html,Arrays,如何使用Javascript从列表中选择元素。以下是我的一些代码: var score = 0; var bin = 0; var question = -1; var answers = ['higher', 'lower', 'higher', 'lower', 'higher']; function answer_question(response) { if (response == 1) { if (an

如何使用Javascript从列表中选择元素。以下是我的一些代码:

    var score = 0;
    var bin = 0;
    var question = -1;
    var answers = ['higher', 'lower', 'higher', 'lower', 'higher'];

    function answer_question(response) {
        if (response == 1) {
            if (answer[question] == "higher"){
                score ++;
                console.log(score);
            } else {
                bin ++;
                console.log("Bin: ");
                console.log(bin);
            }
        }
        else if (response == 0) {
            if (answer[question] == "lower") {
                score ++;
                console.log(score);
            } else {
                bin ++;
                console.log("Bin: ");
                console.log(bin);
            }
        }
    }
但是它不起作用,我认为这是由于

answer[question] == "higher"

谢谢你的帮助

这是因为三件事:

  • 未定义回答。我猜你的意思是回答。这可能只是一个打字错误

  • 即使您回答了[question],那么,
    question=-1
    answers[-1]
    在Javascript中返回
    未定义的
    。JS没有负索引的概念,所以不能使用负数作为索引下标。使用介于
    0
    answers.length-1
    之间的任意数字,如下所示:

    answers[0] // returns 0th (first) element of answers array
    
  • 您从不增加或更改
    问题
    。每次运行此代码时,
    回答[问题]
    总是返回相同的内容。那样的话,你为什么还要说那句话



然而,为了回答您的问题,可以通过如下索引访问数组元素:
array[index]
<代码>索引
可以是介于
0
和小于数组长度1之间的任意整数

问题=-1
?数组以
0
开头。您所说的“在列表中选择一个元素”到底是什么意思?您的代码非常混乱,您能否举例说明这些参数的作用以及调用函数的时间和方式?如何获取
问题的值?第一点可能是问题所在,另外两个可能是因为它是“部分代码”,而不是全部代码。