对值的类型使用 switch 语句的 JavaScript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8734247/
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
JavaScript function that uses switch statement on the type of value
提问by Alex
I've been working with the JavaScript learning modules found in CodeAcademy.comand find myself unredeemed in chapter 4, module 8 (switch - control flow statements)
我一直在使用CodeAcademy.com 中的 JavaScript 学习模块,但发现自己在第 4 章模块 8(开关 - 控制流语句)中没有得到救赎
Please see below for example request:
请参阅下面的示例请求:
// 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 ===
and this is what I was able to code:
这就是我能够编码的内容:
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;
}
Can someone please hint or tell me what is missing here?
有人可以提示或告诉我这里缺少什么吗?
回答by Matt H
You need to use the typeof
operator:
您需要使用typeof
运算符:
var value = true;
switch (typeof value) {
case 'string':
回答by sam
function detectType(value) {
switch (typeof value){
case 'string':
return 'str';
case 'number':
return 'num';
case 'object':
return 'obj';
default:
return 'other';
}
}
you could left out the break;
in this case, because is optional after return;
break;
在这种情况下,您可以省略,因为在之后是可选的return;
回答by maerics
Read the question again - "write a function that uses switch statements on the typeof the value". You're missing anything about the type of the value, try using the typeof
operator.
再次阅读问题-“编写一个对值的类型使用 switch 语句的函数”。您缺少有关值类型的任何信息,请尝试使用typeof
运算符。
typeof "foo" // => "string"
typeof 123 // => "number"
typeof {} // => "object"