在javascript中检查变量类型的最佳方法是什么 [英] what is the best way to check variable type in javascript
问题描述
<script type="text/javascript">
function saveName (firstName) {
function capitalizeName () {
return firstName.toUpperCase();
}
var capitalized = capitalizeName();console.log(capitalized instanceof String);
return capitalized;
}
console.log(saveName("Robert")); // Returns "ROBERT"
</script>
问题:
我想检查大写的类型,所以我使用大写的instanceof String
?但它显示: false
在控制台中,我不想尝试大写的instanceof函数
,对象
...这将花费太多时间,那么检测变量类型的最佳方法是什么?
I want to check the type of capitalized , so I use capitalized instanceof String
? But it shows: false
in console, I do not want to try capitalized instanceof Function
, Object
...It will take too much time, so what is the best way to detect a variable type?
推荐答案
最好的方法是使用 typeof
关键字。
The best way is to use the typeof
keyword.
typeof "hello" // "string"
typeof
运算符将操作数映射到六个值之一:string
,number
,object
,function
,undefined
和 布尔
。 instanceof
方法测试提供的函数的原型是否在对象的原型链中。
The typeof
operator maps an operand to one of six values: "string"
, "number"
, "object"
, "function"
, "undefined"
and "boolean"
. The instanceof
method tests if the provided function's prototype is in the object's prototype chain.
这篇Wikibooks文章以及这篇MDN文章在总结JavaScript的类型方面做得非常好。
This Wikibooks article along with this MDN articles does a pretty good job of summing up JavaScript's types.
这篇关于在javascript中检查变量类型的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!