Piz*_*man 2 javascript character
我在这里看了很多与我有关的问题,但他们都使用不同的方法来处理我必须使用的方法.我知道这是一个非常漫长的方式来找出有更简单的方法,但我只是按照说明.
为什么以下代码不起作用?该函数检查它是否是元音.然后检查输入以查看它的长度是否为1.如果为1,则调用该函数.如果它大于1,则在长度为1之前请求另一个输入.
我现在看到JS中不存在布尔值.我想这个问题现在无效!
function isVowel(x){
boolean result;
if(x == "A" || x == "E" || x == "I" || x == "O" || x == "U" ) {
result = true;
}
else{
result = false;
}
return result;
}
var input;
input = prompt("Enter a character ");
input = input.toUpperCase();
if(input.length == 1){
isVowel(input);
}
}
else{
while(input.length != 1){
prompt("Enter a character ");
if(input.length == 1){
isVowel(input);
}
}
}
alert(isVowel(input));
Run Code Online (Sandbox Code Playgroud)
你isVowel在三个地方打电话,只丢掉前两个的返回值.如果要查看前两个位置的返回值,请显示它(通过alert在上一个示例中,或者其他几种方式).
还有其他问题:
正如devqon所指出的那样,你已经使用boolean而不是var,所以代码不会解析
任何时候你发现自己写作:
var result;
if (condition) {
result = true;
} else {
result = false;
}
return result;
Run Code Online (Sandbox Code Playgroud)
......停下来做吧:
var result = condition;
return result;
Run Code Online (Sandbox Code Playgroud)
因此isVowel:
function isVowel(x) {
var result;
result = x == "A" || x == "E" || x == "I" || x == "O" || x == "U";
return result;
}
Run Code Online (Sandbox Code Playgroud)
(当然,您可以将其设为单行,但以这种方式调试会更容易.)
你}的if块后你有一个额外的(合理,一致的格式化会使这一点变得明显)
您的while循环永远不会结束,因为您永远不会input使用返回值更新prompt
而不是一个if接着是while,使用do-while
这是一个只有这些更改的更新版本
function isVowel(x) {
var result;
result = x == "A" || x == "E" || x == "I" || x == "O" || x == "U";
return result;
}
var input;
do {
input = prompt("Enter a character ");
if (input.length == 1) {
alert(isVowel(input));
}
} while (input.length != 1);Run Code Online (Sandbox Code Playgroud)
小智 7
答案可以是一行,而且简短而甜蜜。见下文。
function isVowel(x) {
return ("aeiouAEIOU".indexOf(x) != -1);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23037 次 |
| 最近记录: |