Javascript 为什么getColor函数总是返回false?

Javascript 为什么getColor函数总是返回false?,javascript,Javascript,我有一个获取用户输入的函数,它应该从选项列表中验证用户输入。函数的最后一部分,在这里我循环遍历结果并返回true,如果结果中有一个true boolean值似乎工作不正常。它不断返回错误 function getColor(){ //gets user color and makes all characters lower case; let color=prompt("Pick a color, your options are white, yell

我有一个获取用户输入的函数,它应该从选项列表中验证用户输入。函数的最后一部分,在这里我循环遍历结果并返回true,如果结果中有一个true boolean值似乎工作不正常。它不断返回错误

    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();

    }
函数getColor(){ //获取用户颜色并使所有字符小写; 让color=prompt(“选择一种颜色,您的选项是白色、黄色、棕色、黑色、棕褐色、红色、橙色”)。toLowerCase(); //储存可接受的颜色 让可接受的颜色=[“白色”、“黄色”、“棕色”、“黑色”、“棕褐色”、“红色”、“橙色”]; 函数验证(){ 让结果=[]; for(设i=0;i 它不断返回错误

Return false
内部
forEach
不会从
getColor
返回,并且您的返回false是无条件的

成功

    return results.some(function(item){
       return item;
    });
这里有一个简单的方法:

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

    }
函数验证(){
让结果=[];

对于(设i=0;i我更喜欢这样做

函数验证(){
返回可接受的颜色。indexOf(color)!=-1;

}
您的整个功能可以简化。无需在数组中按布尔值,然后检查该数组的真实值。只需使用
包含
检查颜色数组是否包含用户提示的颜色

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();

为什么要将内容推送到对象,然后检查真实值?只需在您的条件下使用
return true;
,跳过
else
调用。“为什么我的getColor函数总是返回false?”--因为
validate()
总是返回
false
。请注意,这在任何版本的IE中都不起作用(除非你考虑边)。使用(由IE9+支持)或使用填充物。我实际上不知道@ H2Oooooo。谢谢指点。