对值类型使用switch语句的JavaScript函数
我一直在使用中的JavaScript学习模块,发现自己在第4章模块8(开关-控制流语句)中没有得到重视 请参见以下请求示例:对值类型使用switch语句的JavaScript函数,javascript,Javascript,我一直在使用中的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 i
// 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':
再次阅读问题-“编写一个在值类型上使用switch语句的函数”。如果缺少有关值类型的任何信息,请尝试使用typeof
运算符
typeof“foo”//>“string”
类型123/=>“编号”
{}/=>“对象”的类型
您可以省略
中断代码>在本例中,因为在返回后是可选的代码>开关(值的类型){case“string”:…case“number”:…}
你不应该检查类型吗?嗯,我不知道他们为什么告诉你使用==
。更正。我对===比较感到困惑。“在Java或C这样的语言中,您只能切换少数类型。在JS中,您可以切换任何类型。switch语句中的值将与每种情况下使用===的值进行比较。”@MΓΓБПLL:它比使用=
运算符时计算条件的速度更快。因为使用==
不涉及类型转换/转换,因此:(“1”==1)
返回false。您不需要var value=true代码>
function detectType(value) {
switch (typeof value){
case 'string':
return 'str';
case 'number':
return 'num';
case 'object':
return 'obj';
default:
return 'other';
}
}