是否有用于检查变量类型的快捷语法?

时间:2011-07-05 23:35:54

标签: javascript

在JavaScript中,我该怎么说:

if (typeof obj === 'number' 
    || typeof obj === 'boolean' 
    ||  typeof obj === 'undefined' 
    || typeof obj === 'string') {

换句话说,是否有某种形式:

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

5 个答案:

答案 0 :(得分:6)

您可以使用switch

switch (typeof obj) {
  case 'number':
  case 'boolean':
  case 'undefined':
  case 'string':
    // You get here for any of the four types
    break;
}

在Javascript 1.6中:

if (['number','boolean','undefined','string'].indexOf(typeof obj) !== -1) {
  // You get here for any of the four types
}

答案 1 :(得分:4)

你可以用

之类的东西来近似它
var acceptableTypes = {'boolean':true,'string':true,'undefined':true,'number':true};

if ( acceptableTypes[typeof obj] ){
  // whatever
}

或更详细的

if ( typeof obj in acceptableTypes){
  // whatever
}

答案 2 :(得分:3)

是的。 typeof(obj)只返回一个字符串,因此您可以像检查字符串是否在任何字符串集中那样简单地执行:

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

或者你可以让它更短。由于typeof可能返回的唯一“类型”是numberstringboolean objectfunctionundefined,在这种特殊情况下,你可以改为排除。

if (!(typeof(obj) in {'function':'', 'object':''}))
{
  ...
}

答案 3 :(得分:2)

为工厂提供更多支持:

if ( ('object function string undefined').indexOf(typeof x) > -1) {
  // x is an object, function, string or undefined
}

if ( (typeof x).match(/object|function|string|undefined/)) {
  // x is an object, function, string or undefined
}

您希望这只猫皮肤有多少种方式?

答案 4 :(得分:1)

我喜欢在类似情况下使用函数式编程。 因此,您可以使用underscore.js使其更具可读性:

_.any(['number','boolean','undefined','string'], function(t) {
  return typeof(obj) === t; 
});
相关问题