如何测试一个值是字符串还是int

How can I test if a value is a string or an int?

本文关键字:int 一个 字符串 何测试 测试      更新时间:2023-09-26

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

如何测试一个值是字符串还是int?类似。。。

X=?

如果X是Int{}

如果X是字符串{}

谢谢!

您可以使用运算符类型:

var x = 1;
console.log(typeof x);
x = 'asdf';
console.log(typeof x);

打印:

number
string

这里有一个支持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

EDIT:我刚刚重写了一次,并删除了函数的一个关键部分。已修复

或者更紧凑的版本:

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');
    };
})();

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。

使用typeof函数中内置的JavaScript

var s = "string",
    n = 1; // number
if(typeof s == 'string'){
  //do stuff for string
}

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

其他人已经谈到了typeof运算符和Object.prototype.toString的使用,但如果你想专门测试int与任何类型的数字相比,那么你可以做一些变化:

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

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