最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there a shortcut syntax for checking types of variables? - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

5 Answers 5

Reset to default 6

You 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; 
});
发布评论

评论列表(0)

  1. 暂无评论