我正在尝试实现一个功能,要求几个q存储它们返回有趣的句子与这些输入。但它没有工作,没有显示错误,但是列表没有保存用户自己的3个输入,并注意到每次它将输入保存在alist数组中..取代了之前的列表项,但是我想保存所有这三个。
for(i = 0; i < 3; i++) {
var qlist = ["adjective?","Verb?", "noun?"];
var alist = [];
alist[i] = prompt(qlist[i] + "[questions number-" + i + "]");
}
var statement = document.write("There once was a "+ alist[0] + " programmer who once wanted to use javascript to " + alist[1] + " the " + alist[2]);
alert(statement);
答案 0 :(得分:2)
alist需要在循环之外初始化。否则你会覆盖它。
另外,不要警告(声明)这种类型是未定义的。
另外,不要初始化qlist 3次。
let alist = [];
let qlist = ["adjective?","Verb?", "noun?"];
for(let i = 0; i < 3; i++) {
alist[i] = prompt(qlist[i] + "[questions number-" + i + "]");
}
let statement = document.write("There once was a "+ alist[0] + " programmer who once wanted to use javascript to " + alist[1] + " the " + alist[2]);
答案 1 :(得分:1)
你的alist是在for循环中定义的,你需要把它放在外面:
var qlist = ["adjective?","Verb?", "noun?"];
var alist = [];
for(i = 0; i < 3; i++) {
alist[i] = prompt(qlist[i] + "[questions number-" + i + "]");
}
var statement = document.write("There once was a "+ alist[0] + " programmer who once wanted to use javascript to " + alist[1] + " the " + alist[2]);
alert(statement);