Javascript 有人能帮我写这个简单的代码吗?
结果是:真、假、假 它应该是:真,真,假 有人能帮我解释为什么会发生这种事吗 我只是在勉强学习JavaScriptJavascript 有人能帮我写这个简单的代码吗?,javascript,Javascript,结果是:真、假、假 它应该是:真,真,假 有人能帮我解释为什么会发生这种事吗 我只是在勉强学习JavaScript 还有,有没有办法重构这段代码?我不想对每一个新情况重复我自己。你需要像这样分开|s: function isVowel(char){ if(typeof char == 'string' && char.length > 1){ console.log('not a char'); return 'not a char
还有,有没有办法重构这段代码?我不想对每一个新情况重复我自己。你需要像这样分开
|
s:
function isVowel(char){
if(typeof char == 'string' && char.length > 1){
console.log('not a char');
return 'not a char';
} else {
if (char.toLowerCase() === ('a'||'e'||'i'||'o'||'u')){
console.log(char, true);
return true;
} else {
console.log(char, false);
return false;
}
}
}
document.writeln(isVowel('a'));
document.writeln(isVowel('e'));
document.writeln(isVowel('l'));
char.toLowerCase() === 'a'
|| char.toLowerCase() === 'e'
|| char.toLowerCase() === 'i'
|| char.toLowerCase() === 'o'
|| char.toLowerCase() === 'u'
而不是像这样:
function isVowel(char){
if(typeof char == 'string' && char.length > 1){
console.log('not a char');
return 'not a char';
} else {
if (char.toLowerCase() === ('a'||'e'||'i'||'o'||'u')){
console.log(char, true);
return true;
} else {
console.log(char, false);
return false;
}
}
}
document.writeln(isVowel('a'));
document.writeln(isVowel('e'));
document.writeln(isVowel('l'));
char.toLowerCase() === 'a'
|| char.toLowerCase() === 'e'
|| char.toLowerCase() === 'i'
|| char.toLowerCase() === 'o'
|| char.toLowerCase() === 'u'
以下是上述内容的一部分:
- 问题就在这里
char.toLowerCase() === ('a'||'e'||'i'||'o'||'u')
相等运算符不“分布”,您必须针对每个可能性单独测试输入。一个简洁的解决方案可能是
if (char.toLowerCase() === ('a'||'e'||'i'||'o'||'u'))
('a'| | | | | | | | | | | | | | | | | | | | | | | | | | | 124
要确认上述内容,请使用控制台进行尝试,或:
if ("aeiou".indexOf(char.toLowerCase()) + 1) {
console.log(char, true);
return true;
}
我的建议是:
console.log(('a'||'e'||'i'||'o'||'u'));
完整版本:
' aeiou'.indexOf(char) > 0
重构版本:
function isVowel(char){
if(typeof char == 'string' && char.length > 1){
console.log('not a char');
return 'not a char';
} else {
if (' aeiou'.indexOf(char) > 0){
console.log(char, true);
return true;
} else {
console.log(char, false);
return false;
}
}
}
document.writeln(isVowel('a'));
document.writeln(isVowel('e'));
document.writeln(isVowel('l'));
为什么要投否决票?我只是勉强学会了javascript…我想投票的结果是因为问题的标题。。。“有人能帮我吗?”并没有描述你的问题。。。你看?@J.Bruni什么标题会更好?“确定字符是否是元音的函数不起作用”可能不是最好的标题,但我认为它已经好了一点。@J.Bruni是的,听起来确实更好。谢谢。。只是想知道。。做这件事的最好方法是什么,而不是一遍又一遍地重复我自己?@JanCarloViray,看看我的答案。是一种适合这种情况的结构。JS没有它们,但您可以轻松地使用对象(即{}
)进行模拟,例如:。对于少量的这些,在数组上循环应该是很好的-也就是说,制作一个数组var元音=['a','e','i','o','u']
,然后使用For
遍历每个值并进行检查。或者不要重新发明,只使用已经完成的内容:indexOf
查找搜索字符串的位置。如果找不到,则返回-1
。它正在为您做所有的工作==更简单的代码。@Paisle:“aeiou”。indexOf(“a”)
将返回0
(零)并计算为false
-您上面的代码将给出错误的结果results@paislee:如果你指的是“indexOf”用法,那么我没有违背你的想法;只有在我准备添加“重构版本”时,我才使用您评论中的-1
信息改进了代码。请注意regex
解决方案几乎总是比indexOf
算法慢。这可能是关键循环中的一个问题。