创建一个接收整数作为参数并返回字符串的函数,例如:
这可以使用 3 个 if 语句来完成,如下所示,但是可以只使用 2 个 if 语句来完成吗?
const intToStr = (intVal) => {
if (intVal % 4 == 0 && intVal % 7 == 0) {
return "FooBar";
}
if (intVal % 7 == 0) {
return "Bar";
}
if (intVal % 4 == 0) {
return "Foo";
}
}
console.log(intToStr(4*7));
console.log(intToStr(7));
console.log(intToStr(4));Run Code Online (Sandbox Code Playgroud)
是的,只需 2 个 if 语句即可完成。
const intToStr = (intVal) => {
let str = '';
if (intVal % 4 === 0) {
str += "Foo";
}
if (intVal % 7 === 0) {
str += "Bar";
}
return str;
}
console.log(intToStr(4*7));
console.log(intToStr(7));
console.log(intToStr(4));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
68 次 |
| 最近记录: |