0

嘿,请帮我解决这个问题,我想添加许多变量并让他们检查数组,但它不起作用。我希望它检查文本框中的所有文本,如果它与数组相同,那么它将提供警报。这是我的代码

function setValue(){
myVariable= document.forms["myform"]["gname"].value;
myVariable1= document.forms["myform"]["graphic"].value;
myVariable2= document.forms["myform"]["gpc"].value;
myVariable3= document.forms["myform"]["procesor"].value;
myVariable4= document.forms["myform"]["ram"].value;
myVariable5= document.forms["myform"]["os"].value;
var graphic = ["radeon hd", "nvidia"];
var gname = ["prince of persia", "grand theft auto"];
var gpc = ["radeon hd 121", "nvidia 121"];
var procesor = ["intel i7", "intel i5", "intel i3"];
var os = ["Windows 7", "Windows 8", "Windows xp"];
var ram = ["4 Gb", "8 Gb", "12 Gb"];
    var canRun = false;

for(i=0;i<ram.length;i++)
(i=0;i<gpc.length;i++)
(i=0;i<os.length;i++)
(i=0;i<procesor.length;i++)
(i=0;i<gname.length;i++)
(i=0;i<graphic.length;i++)

    {
        if (myVariable5 === os[i] && myVariable4 === ram[i] && myVariable3 === procesor[i] && myVariable2 === gpc[i] && myVariable1 === graphic[i] && myVariable === gname[i]) 
        {   
            canRun = true;  
        }
    }

    if (canRun)
    {   
        alert("yes this game can run");
    }
    else 
    {       
        alert("No, This game cannot run");
    }
};
4

4 回答 4

1

你不能for像那样把循环混在一起。您需要为每个数组创建一个单独的循环,或者更简单地说,使用它indexOf来代替。

于 2013-10-14T19:13:20.940 回答
0

您可以一次运行一个循环,如下所示:

var ok_count = 0;
for(i=0;i<ram.length;i++) {
    (myVariable4 === ram[i]) {
         ok_count++;
         break;
    }
}
for (i=0;i<gpc.length;i++) {
    (myVariable2 === gpc[i]) {
         ok_count++;
         break;
    }
}
if (ok_count == 2) { 
       // MATCH :-D
}
else {
       // NO MATCH :-(
}
于 2013-10-14T19:13:54.183 回答
0

你可以使用类似的东西

function setValue(){
    var canRun = true,
        accepted = {
            graphic: ["radeon hd", "nvidia"],
            gname: ["prince of persia", "grand theft auto"],
            gpc: ["radeon hd 121", "nvidia 121"],
            procesor: ["intel i7", "intel i5", "intel i3"],
            os: ["Windows 7", "Windows 8", "Windows xp"],
            ram: ["4 Gb", "8 Gb", "12 Gb"]
        };
    for(var i in accepted){
        // If you have modified `Object.prototype`, you should also check
        // `accepted.hasOwnProperty(i)`
        if(accepted[i].indexOf(document.forms['myform'][i].value) === -1) {
            canRun = false;
            break;
        }
    }
    alert(canRun ? "yes this game can run" : "No, This game cannot run");
}
于 2013-10-14T19:20:53.633 回答
0

您似乎正在尝试查看提交的值是否在有效值范围内。只需使用Array.prototype.indexOf

if (graphic.indexOf(myVariable1) >= 0 && ram.indexOf(myVariable2) && ...) {
    canRun = true;
}

上面的代码说:如果graphic数组包含从表单提交的值,则将其标记为有效(并检查其他字段)。

我非常喜欢下划线,你也可以使用它。

if (_.contains(graphic, myVariable1) && _.contains(ram, myVariable2) && ...) {
于 2013-10-14T19:21:45.283 回答