【发布时间】:2020-09-11 15:10:06
【问题描述】:
在下面的代码中,我试图创建一个 switch 语句,它接受以下输入:34, '34', {input: 34}, hello, ["hello"]
并在每个输入中返回数字 34,我需要的情况是:
If given a number, return the number
If given a string, convert it to a number and return the result
If given an object, return the value of the input property
Otherwise, throw an error: "Unexpected data type"
我遇到了对象输入问题。非常感谢!
function parseNumber(unknown) {
switch(unknown) {
case 34:
return unknown;
case '34':
return parseInt(unknown);
case unknown.input:
return unknown.input;
default:
throw new Error("Unexpected data type");
}
}
【问题讨论】:
-
你为什么要准确检查 34?这个问题并不像您应该准确检查 34 。 Switch 似乎也是一个糟糕的选择。
-
这是问题的要求。我无法控制它应该检查什么。它要求匹配数字 34 的案例。
-
传入的数字是34.....我不认为这意味着匹配34
"If given a number, return the number" -
@Shuken 这些只是不同类型的示例,并不是唯一可能的值。
标签: javascript object switch-statement