开发者

Is there a shortcut syntax for checking types of variables?

开发者 https://www.devze.com 2023-03-18 01:29 出处:网络
In JavaScript, how do I say: if (typeof obj === \'number\' typeof obj === \'boolean\' typeof obj === \'undefined\'

In JavaScript, how do I say:

if (typeof obj === 'number' 
    || typeof obj === 'boolean' 
    ||  typeof obj === 'undefined' 
    || typeof obj ===开发者_如何学C 'string') {

In other words, is there some kind of:

if (typeof obj in('number','boolean','undefined','string')) {


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

精彩评论

暂无评论...
验证码 换一张
取 消