我有一个if else语句来匹配一个字符串,元音和辅音工作正常。我想用switch语句对其进行整理,但是使用match()不能作为一种情况。我错过了什么?
if else //返回元音:1,辅音:3
function getCount(words) {
var v,
c;
if (words === '' || words === ' ') {
v=0;
c=0;
} else if(words.match(/[aeiou]/gi)) {
v = words.match(/[aeiou]/gi).length;
c = words.replace(/\s|\W/g, '').split("").length - v;
} else {
v = 0;
c = 0;
}
return {
vowels: v,
consonants: c
};
}
getCount('test');
开关//返回元音:0,辅音:0
function getCount(words) {
var v,
c;
switch(words) {
case words.match(/[aeiou]/gi):
v = words.match(/[aeiou]/gi).length;
c = words.replace(/\s|\W/g, '').split("").length - v;
console.log("true");
break;
case '':
case ' ':
v = 0;
c = 0;
break;
default:
v = 0;
c = 0;
}
return {
vowels: v,
consonants: c
};
}
getCount('test');
答案 0 :(得分:2)
// Code goes here
function getCount(words) {
var v,
c;
switch(true) {
case ( words.match(/[aeiou]/gi) !=null ):
v = words.match(/[aeiou]/gi).length;
c = words.replace(/\s|\W/g, '').split("").length - v;
console.log("true");
break;
case (words==''):
case (words==' '):
v = 0;
c = 0;
break;
default:
v = 0;
c = 0;
}
return {
vowels: v,
consonants: c
};
}
console.log(getCount('test'));

答案 1 :(得分:1)
您的switch语句需要计算表达式并将结果与每个case语句的值进行比较。
function getCount(words) {
var v,
c;
switch(words.match(/[aeiou]/gi).length > 0) {
case true:
v = words.match(/[aeiou]/gi).length;
c = words.replace(/\s|\W/g, '').split("").length - v;
console.log("true");
break;
default:
v = 0;
c = 0;
}
return {
vowels: v,
consonants: c
};
}
getCount('test');