[英]In javascript, does the new operator always return an object of same type which is mentioned in the new statement?
[英]javascript prompt return type is object always?
function check_color(){ color_input = prompt("I am thinking of one of these colors: \\n\\n"+ "blue, cyan, gold, gray, magenta, orange, red, white, yellow \\n\\n"+ "What color am I thinking of?"); if(color_input != null || color_input != undefined){ if(typeof (color_input) != 'string') { alert("This is not any color. \\n\\n"+ "Please enter color in text format"); return false; } if(colors.indexOf(color_input) < 0){ alert("Sorry, i don't recognize your color. \\n\\n"+ "Please try again"); return false; } } else{ alert("Please enter some input"); return false; } }
为什么在尝试运行此代码时总是执行first-if块? 有人可以解释一下吗?
“颜色”在哪里if(colors.indexOf(color_input)
我在这里收到控制台错误。 请添加颜色数组
我不确定这个问题,但是在jsFiddle中,此代码段按预期工作:
function check_color() {
color_input = prompt("I am thinking of one of these colors: \n\n" +
"blue, cyan, gold, gray, magenta, orange, red, white, yellow \n\n" +
"What color am I thinking of?");
colors = ["blue", "cyan", "gold", "gray", "magenta", "orange", "red", "white", "yellow"];
if (color_input != null) {
if (typeof(color_input) != 'string') {
console.log("This is not any color. \n\n" +
"Please enter color in text format");
return false;
}
if (colors.indexOf(color_input) < 0) {
console.log("Sorry, i don't recognize your color. \n\n" +
"Please try again");
return false;
}
console.log("your color:" + color_input);
} else {
console.log("Please enter some input");
return false;
}
}
check_color();
我必须将颜色数组添加到代码段中(我假设您在其他地方有它)。 我还取出了“ || undefined”,因为提示符仅返回字符串或null。
因此,您可以这样简化代码:
function check_color() {
color_input = prompt("I am thinking of one of these colors: \n\n" +
"blue, cyan, gold, gray, magenta, orange, red, white, yellow \n\n" +
"What color am I thinking of?");
colors = ["blue", "cyan", "gold", "gray", "magenta", "orange", "red", "white", "yellow"];
if (color_input) { // null would be false
if (colors.indexOf(color_input) < 0) {
console.log("Sorry, i don't recognize your color. \n\n" +
"Please try again");
return false;
}
console.log("your color:" + color_input);
} else {
console.log("Please enter some input");
return false;
}
}
check_color();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.