如何在 Javascript 中使用 typeof 和 switch case

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8754288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:29:14  来源:igfitidea点击:

How to use typeof and switch cases in Javascript

javascriptswitch-statementtypeof

提问by stanigator

I'm having problems finding out what's wrong with the code below. I have consulted how to use typeofand switch cases, but I'm lost at this point. Thanks in advance for your advices.

我在找出下面的代码有什么问题时遇到了问题。我已经咨询了如何使用typeofswitch case,但此时我迷路了。预先感谢您的建议。

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

------------- Update -----------------------------------

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

Turns out the problem comes from my mistake (or rather oversight) of not following the instructions properly. Thanks again for your help and comments!

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

回答by qiao

typeofreturns a string, so it should be

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

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

回答by d48

This is the code that will work. I'm going through the codeacademy.com coures also. The issue was with typeOfhaving mixed casing. It's case sensitive and should be all lowercase: typeof

这是将起作用的代码。我也在浏览 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";
  }
}

回答by Ido Green

This is the code the will work for you:

这是将为您工作的代码:

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