【问题标题】:How to use typeof and switch cases in Javascript如何在 Javascript 中使用 typeof 和 switch case
【发布时间】:2012-02-03 23:21:17
【问题描述】:

我在找出以下代码有什么问题时遇到了问题。我已经咨询过如何使用typeofswitch cases,但我现在迷路了。提前感谢您的建议。

// Write a function that uses switch statements on the
// type of value. If it is a string, return 'str'. If it
// is a number, return 'num'. If it is an object, return
// 'obj'. If it is anything else, return 'other'.
function detectType(value) {
  switch (typeof value) {
    case string:
      return "str";
    case number:
      return "num";
    default:
      return "other";
  }
}

------------- 更新 --------------------------------- --

原来问题出在我没有正确遵循说明的错误(或者更确切地说是疏忽)。再次感谢您的帮助和 cmets!

【问题讨论】:

    标签: javascript switch-statement typeof


    【解决方案1】:

    typeof返回一个字符串,所以应该是

    function detectType(value) {
      switch (typeof value) {
        case 'string':
          return "str";
        case 'number':
          return "num";
        default:
          return "other";
      }
    }
    

    【讨论】:

    • 这给我带来了另一个问题。什么时候用单引号,什么时候用双引号?
    • 真的没关系,我在上面的例子中输入了单引号只是因为这是我个人的喜好。有关该问题的更多详细信息,请参阅stackoverflow.com/questions/242813/…
    【解决方案2】:

    这是适合您的代码:

    function detectType(value) {
      switch (typeof value) {
      case "string":
         return "str";
      case "number":
         return "num";
      default:
         return "other";
      }
    }
    

    【讨论】:

      【解决方案3】:

      这是可以工作的代码。我也正在浏览 codeacademy.com 课程。问题在于 typeOf 有混合大小写。它区分大小写并且应该全部小写:typeof

      function detectType(value) {
        switch(typeof value){
          case "string":
            return "str";
          case "number":
            return "num";
          case "object":
            return "obj";
          default:
            return "other";
        }
      }
      

      【讨论】:

        【解决方案4】:

        typeof 返回一个字符串,所以你应该用单引号将你的 switch case 括起来。

        
        function detectType(value) {
          switch (typeof value) {
            case 'string': // string should me 'string'
              return "string";
            case 'number':
              return "number";
            default:
              return "other";
          }
        }
        

        ?

        【讨论】:

          猜你喜欢
          • 2011-07-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-02-25
          • 1970-01-01
          相关资源
          最近更新 更多