admin管理员组文章数量:1389754
In JavaScript, how do I say:
if (typeof obj === 'number'
|| typeof obj === 'boolean'
|| typeof obj === 'undefined'
|| typeof obj === 'string') {
In other words, is there some kind of:
if (typeof obj in('number','boolean','undefined','string')) {
In JavaScript, how do I say:
if (typeof obj === 'number'
|| typeof obj === 'boolean'
|| typeof obj === 'undefined'
|| typeof obj === 'string') {
In other words, is there some kind of:
if (typeof obj in('number','boolean','undefined','string')) {
Share
Improve this question
edited Jul 5, 2011 at 23:39
user456814
asked Jul 5, 2011 at 23:35
Phillip SennPhillip Senn
47.7k91 gold badges261 silver badges378 bronze badges
2
- Are you looking to improve on the first statement? – Declan Cook Commented Jul 5, 2011 at 23:39
- Just curious -- why do you need to check for so many types? I've never had to do this before. – Casey Chu Commented Jul 6, 2011 at 4:13
5 Answers
Reset to default 6You can use a switch
:
switch (typeof obj) {
case 'number':
case 'boolean':
case 'undefined':
case 'string':
// You get here for any of the four types
break;
}
In Javascript 1.6:
if (['number','boolean','undefined','string'].indexOf(typeof obj) !== -1) {
// You get here for any of the four types
}
You could approximate it with something like
var acceptableTypes = {'boolean':true,'string':true,'undefined':true,'number':true};
if ( acceptableTypes[typeof obj] ){
// whatever
}
or the more verbose
if ( typeof obj in acceptableTypes){
// whatever
}
Yes there is. typeof(obj)
just returns a string, so you can simply do as you would when checking if a string is in any set of strings:
if (typeof(obj) in {'number':'', 'boolean':'', 'undefined':'', 'string':''})
{
...
}
Or you could make it even shorter. Since the only "types" that typeof
may return are number
, string
, boolean
object
, function
and undefined
, in this particular case, you could just make an exclusion instead.
if (!(typeof(obj) in {'function':'', 'object':''}))
{
...
}
More grist for the mill:
if ( ('object function string undefined').indexOf(typeof x) > -1) {
// x is an object, function, string or undefined
}
or
if ( (typeof x).match(/object|function|string|undefined/)) {
// x is an object, function, string or undefined
}
How many ways do you want this cat skinned?
I like to use functional programming for similar situations. So you can use underscore.js to make it more readable:
_.any(['number','boolean','undefined','string'], function(t) {
return typeof(obj) === t;
});
本文标签: javascriptIs there a shortcut syntax for checking types of variablesStack Overflow
版权声明:本文标题:javascript - Is there a shortcut syntax for checking types of variables? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744642340a2617196.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论