我试图弄清楚如何将两个不同的条件应用于 switch 语句中的一个输出。例如,我有一个函数可以根据第二个参数获取的参数来设置字符串的样式。第一个和第二个输出没问题,因为它只有一个样式参数,但第三个输出有。我找不到将大写和反转样式应用于字符串的方法。我尝试循环 switch 语句。我想知道是否有好的解决方案。
function caseStyle(string, style) {
function toUpper(string) {
string = string.toUpperCase();
return string;
}
function toReversed(string) {
string = string.split("").reverse().join("");
return string;
}
switch (style) {
case "upper":
string = toUpper(string);
break;
case "reversed":
string = toReversed(string);
break;
}
return string;
}
console.log(caseStyle("hello", "upper")); //output: HELLO
console.log(caseStyle("hello", "reversed")); //output: olleh
console.log(caseStyle("hello", ["upper", "reversed"])); // expected output: OLLEH
最佳答案
您需要检查 style
是否为数组,并进行相应处理
或者,强制它成为一个数组style = [style].flat()
,然后迭代该数组
在传入数组的情况下,.flat()
会展平数组
如下
function caseStyle(string, style) {
style = [style].flat();
function toUpper(string) {
string = string.toUpperCase();
return string;
}
function toReversed(string) {
string = string.split("").reverse().join("");
return string;
}
style.forEach(style => {
switch (style) {
case "upper":
string = toUpper(string);
break;
case "reversed":
string = toReversed(string);
break;
}
});
return string;
}
console.log(caseStyle("hello", "upper")); //output: HELLO
console.log(caseStyle("hello", "reversed")); //output: olleh
console.log(caseStyle("hello", ["upper", "reversed"])); // expected output: OLLEH
关于javascript - Switch语句: Applying Multiple Arguments in One Output,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75077629/