【问题标题】:Use switch to take in unknown data types, issue with taking in an object使用 switch 接收未知数据类型,接收对象时出现问题
【发布时间】: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


【解决方案1】:

您可以在 switch 案例中使用typeof result 来确定输出:

/*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) {
  const type = typeof unknown;
  //typeof null is object so throwing error
  if (!unknown) throw new Error("Unexpected data type");
  //for non numeric strings throwing error
  if (type === "string" && Object.is(+unknown, NaN)) throw new Error("Unexpected data type");
  //typeof Array is object so excluding arrays
  if (Array.isArray(unknown)) throw new Error("Unexpected data type");
  if (type === "object" && !unknown.hasOwnProperty("input")) throw new Error("Unexpected data type");
  
  switch (type) {
    case "number":
      return unknown;
    case "string":
      return +unknown;
    case "object":
      return unknown.input;
    default:
      throw new Error("Unexpected data type");
  }
}
console.log(parseNumber(34));
console.log(parseNumber('34'));
console.log(parseNumber({input: 34}));
//Error cases
try{
console.log(parseNumber("hello"));
}catch(e){console.error(e)}

try{
console.log(parseNumber());
}catch(e){console.error(e)}

try{
console.log(parseNumber(() => "hello"));
}catch(e){console.error(e)}

try{
console.log(parseNumber([34]));
}catch(e){console.error(e)}

try{
console.log(parseNumber({"foo": "bar"}));
}catch(e){console.error(e)}

【讨论】:

  • case "object" && !Array.isArray(unknown): case true 或case false.....
  • @epascarello 可能不好,已修复。
  • @FullstackGuy 谢谢,太好了。我对如何使用开关有错误的逻辑类型,这真的很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-05
  • 2019-12-14
相关资源
最近更新 更多