我为我的rails应用程序编写了一个javascript测验,其中每个问题只有两个答案之间可供选择,我现在正在尝试扩展它以便有四个问题和四个结果页面,但没有到目前为止能够使它工作。有人可以帮忙吗?我已经尝试过更改var计算但到目前为止还没有成功。
function generateResult(answers) {
var panda = bear = 0;
for(var i =0; i < answers.length; i++){
if(answers[i] == 1){
bear++;
}
else {
panda++;
}
}
if(bear > panda) {
return "sbear.html";
}
else if(bear > elephant) {
return "sbear.html";
}
else if(bear > alpacha) {
return "sbear.html";
}
else if(panda > bear) {
return "sbear.html";
}
else if(panda > elephant) {
return "sbear.html";
}
else if(panda > alpacha) {
return "rpanda.html";
}
else if(alpacha > bear) {
return "sbear.html";
}
else if(alpacha > panda) {
return "sbear.html";
}
else if(alpacha > elephant) {
return "alpach.html";
}
else {
return "eleph.html";
}
}
答案 0 :(得分:1)
这是另一个答案。我为我假设的答案列表工作
var answers = [1,2,3,4,2,2,2,3,4]
function generateResult(answers) {
var animals = {
1: 'bear',
2: 'panda',
3: 'elephant',
4: 'alpacha'
}
var counts = [0,0,0,0];
answers.forEach(function(answer){
counts[answer-1]++;
});
return animals[counts.indexOf(Math.max(...counts))+1] + '.html';
}
结果:
genarateResult(答案); //'panda.html'
答案 1 :(得分:0)
我不确定这些是熊/熊猫/大象/ alpac(h)a的正确值,但你可以很容易地交换它们。
function generateResult(answers) {
// initialize ALL variables
var panda = bear = elephant = alpacha = 0;
for(var i =0; i < answers.length; i++){
if(answers[i] == 1){ // assuming bear == 1
bear++;
}
else if(answers[i] == 2) { // assuming panda == 2
panda++;
}
else if(answers[i] == 3) { // assuming elephant == 3
elephant++;
}
else { // assuming alpacha == 4
alpacha++;
}
}
if (bear > alpacha && bear > panda && bear > elephant) {
return "sbear.html";
}
else if (alpacha > bear && alpacha > panda && alpacha > elephant) {
return "alpach.html";
}
else if (panda > alpacha && panda > bear && panda > elephant) {
return "rpanda.html";
}
else {
return "eleph.html";
}
}