对值的类型使用switch语句的JavaScript函数

JavaScript function that uses switch statement on the type of value

本文关键字:语句 JavaScript switch 函数 类型      更新时间:2023-09-26

我一直在使用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 ===

这就是我能够编码的:

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

有人能告诉我这里少了什么吗?

您需要使用typeof运算符:

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

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

再次阅读问题-"编写一个在值的类型上使用switch语句的函数"。如果缺少有关值类型的任何内容,请尝试使用typeof运算符。

typeof "foo" // => "string"
typeof 123 // => "number"
typeof {} // => "object"