在做警报时,第一个元素的索引,即紫色正在显示-1。但是这对于获得正确的结果是意外的。因此我无法得到任何人帮助我的预期结果以便我可以去进一步编码。实际上是javascript的新手,所以我遇到了这样的问题。希望你能尽快回答。
var colors = ["voilet", "indigo", "blue", "green", "yellow", "orange", "red"];
var target;
var target_index;
var guess_input;
var finished = false;
function do_game() {
var random_number = Math.random() * 7;
var random_number_integer = Math.floor(random_number);
var target_index = random_number_integer;
target = colors[target_index];
alert(target);
while (!finished) {
var guess_input = prompt("I am thinking of a color " +
"violet,indigo,blue,green,yellow,orange,red" +
"What is the color?");
alert(colors.indexOf(guess_input));
finished = check_guess();
}
}
function check_guess() {
if (colors.indexof(guess_input) < 0) {
alert('not present');
return false;
}
if (guess_input > target) {
alert('you gave large');
return false;
}
if (guess_input < target) {
alert('you gave small');
return false;
}
return true;
}
答案 0 :(得分:5)
您说guess_input
为violet
并返回-1
这是正常行为,因为数组中不存在violet
["voilet","indigo","blue","green","yellow","orange","red"];
存在拼写错误:您写了voilet
而不是violet
答案 1 :(得分:0)
guess_input
在var
函数内部使用do_game
定义,因此它不是全局的。
您需要删除var
,以便可以在其他方法中访问它或将其传递给其他方法。
/* fixed spelling here */
var colors = ["violet", "indigo", "blue", "green", "yellow", "orange", "red"];
var target;
var target_index;
var guess_input;
var finished = false;
function do_game() {
var random_number = Math.random() * 7;
var random_number_integer = Math.floor(random_number);
var target_index = random_number_integer;
target = colors[target_index];
alert(target);
while (!finished) {
/* removed var here */
guess_input = prompt("I am thinking of a color " +
"violet,indigo,blue,green,yellow,orange,red" +
"What is the color?");
alert(colors.indexOf(guess_input));
finished = check_guess();
}
}
function check_guess() {
/* fixed typo here */
if (colors.indexOf(guess_input) < 0) {
alert('not present');
return false;
}
if (guess_input > target) {
alert('you gave large');
return false;
}
if (guess_input < target) {
alert('you gave small');
return false;
}
return true;
}
do_game()
&#13;
答案 2 :(得分:0)
检查阵列中紫罗兰的拼写。
和
if (colors.indexof(guess_input) < 0) {
alert('not present');
return false;
}
你也有拼写错误。它应该是:
colors.indexOf(guess_input)