javascript - 如何在 Javascript 中使用 typeof 和 switch cases

标签 javascript switch-statement typeof

我无法找出下面代码的问题。我咨询过如何使用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";
  }
}

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

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

最佳答案

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

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

关于javascript - 如何在 Javascript 中使用 typeof 和 switch cases,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8754288/

相关文章:

javascript - Html5 音频标签在 iOS7 设备上不起作用

javascript - 我可以从链式 AJAX 调用生成一系列 Rx Observables 吗?

c - Switch 语句用法 - C

c# - TypeCode 与 typeof

c - 使用 typeof 将变量声明转换为类型?

javascript - 检查 JavaScript 函数是否是 jQuery 元素的方法

javascript - HTML 链接到 anchor 而不更改 url

javascript - jquery sleep 未在 ajax 请求上执行

c++ - 在 switch 语句中初始化时 undefined variable ?

c# - 你如何处理对象类型切换?