如何在Javascript中使用typeof和switch案例

如何在Javascript中使用typeof和switch案例,javascript,switch-statement,typeof,Javascript,Switch Statement,Typeof,我发现下面的代码有什么问题。我已经咨询过如何使用和,但现在我不知所措。提前谢谢你的建议 // 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, ret

我发现下面的代码有什么问题。我已经咨询过如何使用和,但现在我不知所措。提前谢谢你的建议

// 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";
  }
}
-------------更新-----------------------------------


事实证明,问题来自我的错误(或者更确切地说是疏忽),没有正确地遵循说明。再次感谢您的帮助和评论

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

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

这是将为您工作的代码:

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

这是可以工作的代码。我也在浏览codeacademy.com网站。问题在于类型的具有混合外壳。它区分大小写,应该全部小写:typeof

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

typeof
返回一个字符串,因此您应该在单引号之间封装开关大小写


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

这给我带来了另一个问题。我什么时候应该使用单引号,什么时候应该使用双引号?这真的没关系,我在上面的例子中键入单引号只是因为这是我个人的偏好。有关该问题的更多详细信息,请参阅