所以我试图制作一个简单的验证器来验证用户对预定义数组的输入。当所有输入都有效时,我想让他们发送"发送"我的代码中的输入转发。
代码的问题是循环。我做了3个循环如下:
for (x = 0; x < validates.length; x++) {
for (i = 0; i < validates[x].length; i++) {
for (y = 0; y < inputs.length; y++) {
console.warn(inputs[y]);
console.warn(validates[x]);
if (inputs[y].toLowerCase().indexOf(validates[x]) !== -1) {
console.warn("vali1 == " + validates[x] + "!");
found += "t";
break;
}else {
found += "f";
}
}break;
}break;
}
JsFiddle. 我知道我可以通过制作3个单独的循环来使代码变得更容易。但我希望继续使用我的代码来成为更好的作家。
所以我的问题是为什么这不起作用,为什么?有没有其他选择或者我是否在正确的轨道上?谢谢!
答案 0 :(得分:1)
一种有效的替代方法是重构代码以减少循环次数。
var valid_vals = { 'region': ["aridia", "black rise", "branch", "cache", "catch", "cloud ring", "cobalt edge", "curse", "deklein", "delve", "derelik", "detorid", "devoid", "domain", "esoteria", "essence", "etherium reach", "everyshore", "fade", "feythabolis", "fountain", "geminate", "genesis", "great wildlands", "heimatar", "immensea", "impass", "insmother", "kador", "khanid", "kor-azor", "lonetrek", "malpais", "metropolis", "molden heath", "oasa", "omist", "outer passage", "outer ring", "paragon soul", "period basis", "perrigen falls", "placid", "providence", "pure blind", "querious", "scalding pass", "sinq laison", "solitude", "stain", "syndicate", "tash-murkon", "tenal", "tenerifis", "the bleak lands", "the citadel", "the forge", "the kalevala expanse", "the spire", "tribute", "vale of the silent", "venal", "verge vendor", "wicked creek"],
'ship': ["venture", "procurer", "retriever", "covetor", "skiff", "mackinaw", "hulk"],
'ore': ["veldspar", "concentrated veldspar", "dense veldspar", "scordite", "condensed scordite", "massive scordite", "pyroxeres", "solid pyroxeres", "viscous pyroxeres", "plagioclase", "azure plagioclase", "rich plagioclase", "omber", "silvery omber", "golden omber", "kernite", "luminous kernite", "fiery kernite", "jaspet", "pure jaspet", "pristine jaspet", "hemorphite", "vivid hemorphite", "radiant hemorphite", "hedbergite", "vitric hedbergite", "glazed hedbergite", "gneiss", "iridescent gneiss", "prismatic gneiss", "dark ochre", "onyx ochre", "obsidian ochre", "spodumain", "bright spodumain", "gleaming spodumain", "crokite", "sharp crokite", "crystalline crokite", "bistot", "triclinic bistot", "monoclinic bistot", "arkonor", "crimson arkonor", "prime arkonor", "mercoxit", "magma mercoxit", "vitreous mercoxit"]
};
$("#check").click(function () {
// validation code
var all_valid = true;
$('input.validate').each(function () {
if ($.inArray($(this).val(), valid_vals[$(this).attr('id')]) === -1) {
console.log($(this).attr('id') + ' did not validate');
all_valid = false;
}
});
if (all_valid)
console.log("All fields validated");
});
JSFiddle:https://jsfiddle.net/tcf6gg1b/2/