如何在Javascript中使用typeof和switch cases

26

我在找出下面代码的问题方面遇到了困难。我已经查阅了如何使用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";
  }
}

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

事实证明,问题出在我没有正确遵循指示,而是疏忽大意。再次感谢您的帮助和评论!

4个回答

38

typeof返回字符串,因此应该是

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

这给我带来了另一个问题。何时应该使用单引号,何时应该使用双引号? - stanigator
1
真的没有关系,我在上面的例子中只是因为个人偏好而打了单引号。有关该问题的更多详细信息,请参见https://dev59.com/OXVC5IYBdhLWcg3wnCWA。 - qiao

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";
  }
}

1

typeof 返回一个字符串,因此您应该在单引号之间包含您的 switch case。


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


1

这是能为您工作的代码:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接