如何测试一个值是字符串还是整数?

3

可能是重复问题:
在JavaScript中查找变量类型

如何测试一个值是字符串还是整数?类似于...

X = ?

如果X是整数 {}

如果X是字符串 {}

谢谢!


如果您描述一下您真正想解决的问题,我们可能可以提供更好的帮助。 - jfriend00
5个回答

8
您可以使用 typeof运算符:
var x = 1;
console.log(typeof x);
x = 'asdf';
console.log(typeof x);

输出:

number
string

3
这里有一个函数,它优先使用typeof,但在需要时默认使用Object.prototype.toString(速度较慢)
这样一来,就可以处理一些意外的值,比如new String('x')null/regex/(在Chrome中)等。
var type = (function () {
    var toString = Object.prototype.toString,
        typeof_res = {
            'undefined': 'undefined',
            'string': 'string',
            'number': 'number',
            'boolean': 'boolean',
            'function': 'function'
        },
        tostring_res = {
            '[object Array]': 'array',
            '[object Arguments]': 'arguments',
            '[object Function]': 'function',
            '[object RegExp]': 'regexp',
            '[object Date]': 'date',
            '[object Null]': 'null',
            '[object Error]': 'error',
            '[object Math]': 'math',
            '[object JSON]': 'json',
            '[object Number]': 'number',
            '[object String]': 'string',
            '[object Boolean]': 'boolean',
            '[object Undefined]': 'undefined'
        };
    return function type(x) {
        var the_type = typeof_res[typeof x];
        return the_type && (the_type !== 'function' || (x.apply && x.call)) ?
            the_type :
            tostring_res[toString.call(x)] || (x ? 'object' : 'null');
    };
})();

type( new String('test') ); // string
type( function(){} );       // function
type( null );               // null
type( /regex/ );            // regexp

编辑:我刚刚进行了重写,但删除了函数的一个关键部分。已修复。

或者更紧凑的版本:

var type = (function() {
    var i, lc, toString = Object.prototype.toString,
        typeof_res = {},
        tostring_res = {},
        types = 'Undefined,String,Number,Boolean,Function,Array,Arguments,RegExp,Date,Null,Error,Math,JSON'.split(',');
    for (i = 0; i < types.length; i++) {
        lc = types[i].toLowerCase();
        if (i < 5) typeof_res[lc] = lc;
        tostring_res['[object ' + types[i] + ']'] = lc;
    }

    return function type(x) {
        var the_type = typeof_res[typeof x];
        return the_type && (the_type !== 'function' || (x.apply && x.call)) ? 
            the_type : 
            tostring_res[toString.call(x)] || (x ? 'object' : 'null');
    };
})();

2

typeof 大多数情况下都能胜任。但如果你的 NumberString 不是原始类型,它将返回 'object'。一般来说,这不是你想要的。

var str = new String('Hello');
typeof str; // 'object'

typeof也将null称为'object',在WebKit中,一个正则表达式是一个'function'。 我认为typeof的主要优点是可以检查变量而不会抛出ReferenceError异常。

您还可以检查变量的constructor属性,或者使用variable instanceof String。但是,在使用跨window代码时,在多个window环境中,这两者都无法使用。

确定类型的另一种保证方式是使用...

var getType = function(variable) {
    return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
}

jsFiddle.


我记得大约一个月前你向我解释过这个。 - Jared Farrish
typeof str; // 'number' 这个应该是来自IE5的。 ;) - user113716

0

使用 JavaScript 内置的 typeof 函数

var s = "string",
    n = 1; // number

if(typeof s == 'string'){
  //do stuff for string
}


if(typeof n == 'number'){
  //do stuff for number
}

0

其他人已经谈论了typeof运算符和使用Object.prototype.toString,但如果您想特别测试整数与任何类型的数字相比,则可以执行以下某种变体:

function isInt(n) {
   return typeof n === "number" && n === Math.floor(n);
}

(如果需要,插入所有的Object.prototype.toString内容。)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接