我有一个获取用户输入的函数,它应该从选项列表中验证用户输入。函数的最后一部分,我遍历结果并返回true,如果结果中的真值布尔值似乎没有正常工作。它不断返回虚假。
function getColor(){
//gets user color and makes all characters lower case;
let color=prompt("Pick a color, your options are white, yellow, brown, black, tan, red, orange").toLowerCase();
//stores acceptable colors
let acceptableColors=["white","yellow", "brown", "black","tan","red","orange"];
function validate(){
let results=[];
for(let i=0; i<acceptableColors.length; i++){//loops through and stores a true value in results if user color is in list of acceptableColors
if(color===acceptableColors[i]){
results.push(true);
}
else{
results.push(false);
}
}
results.forEach(function(item){//loops through results to search for true value and returns true, if it finds one
if(item===true){
return true
}
});
return false;//returns false if user entered invalid color
}
return validate();
}
答案 0 :(得分:2)
它不断返回虚假。
Return false
内{p> forEach
不会从getColor
返回,而您的返回虚假是无条件的
成功
return results.some(function(item){
return item;
});
答案 1 :(得分:0)
这是一个简单的方法:
function validate(){
let results=[];
for(let i=0; i<acceptableColors.length; i++){//loops through and stores a true value in results if user color is in list of acceptableColors
if(color===acceptableColors[i]){
return true;
}
}
return false;//returns false if user entered invalid color
}
答案 2 :(得分:0)
我更喜欢这样做
function validate() {
return acceptableColors.indexOf(color) !== -1;
}
&#13;
答案 3 :(得分:0)
您的整个功能可以简化。没有必要在一个数组中推送布尔值,然后检查该数组的truthy值。只需使用includes
检查颜色数组是否包含用户的提示颜色。
function getColor() {
let color = prompt("Pick a color, your options are white, yellow, brown, black, tan, red, orange").toLowerCase();
let acceptableColors = ["white", "yellow", "brown", "black", "tan", "red", "orange"];
return acceptableColors.includes(color);
}
getColor();