在函数类型上使用switch语句的JavaScript函数

Ale*_*lex 2 javascript

我一直在使用CodeAcademy.com中的JavaScript学习模块,并在第4章,模块8(开关 - 控制流程语句)中发现自己没有兑现

请参阅下面的示例请求:

// 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'.
// compare with the value in each case using ===
Run Code Online (Sandbox Code Playgroud)

这就是我能够编码的:

function StringTypeOf(value) {
var value = true
switch (true) {
 case string === 'string': 
   return "str"; 
   break;
 case number === 'number':
   return "num"; 
   break;
 case object === 'object':
   return "obj"; 
   break;
 default: return "other";
 }
  return value;
}
Run Code Online (Sandbox Code Playgroud)

有人可以提示或告诉我这里缺少什么吗?

Mat*_*t H 7

您需要使用typeof运算符:

var value = true;
switch (typeof value) {
 case 'string': 
Run Code Online (Sandbox Code Playgroud)


小智 6

function detectType(value) {
  switch (typeof value){
    case 'string':
      return 'str';

    case 'number':
      return 'num';

    case 'object':
      return 'obj';

    default:
      return 'other';
  }
}
Run Code Online (Sandbox Code Playgroud)

break;在这种情况下你可以省略,因为之后是可选的return;