首页 文章

检查变量是否是JavaScript中的字符串

提问于
浏览
1279

如何确定变量是否是JavaScript中的字符串或其他内容?

17 回答

  • 1

    为了扩展@ DRAX的answer,我会这样做:

    function isWhitespaceEmptyString(str)
    {
        //RETURN:
        //      = 'true' if 'str' is empty string, null, undefined, or consists of white-spaces only
        return str ? !(/\S/.test(str)) : (str === "" || str === null || str === undefined);
    }
    

    它还将考虑 nullundefined 类型,它将处理非字符串类型,例如 0 .

  • 1

    我也发现这也很好,而且比其他例子短得多 .

    if (myVar === myVar + '') {
       //its string
    } else {
       //its something else
    }
    

    通过连接空引号,它将值转换为字符串 . 如果 myVar 已经是字符串,则if语句成功 .

  • 18

    这对我来说已经足够了 .

    WARNING: 这不是一个完美的解决方案 . 看到我的帖子的底部 .

    Object.prototype.isString = function() { return false; };
    String.prototype.isString = function() { return true; };
    
    var isString = function(a) {
      return (a !== null) && (a !== undefined) && a.isString();
    };
    

    你可以像下面这样使用它 .

    //return false
    isString(null);
    isString(void 0);
    isString(-123);
    isString(0);
    isString(true);
    isString(false);
    isString([]);
    isString({});
    isString(function() {});
    isString(0/0);
    
    //return true
    isString("");
    isString(new String("ABC"));
    

    WARNING: 这种情况在以下情况下工作不正常:

    //this is not a string
    var obj = {
        //but returns true lol
        isString: function(){ return true; }
    }
    
    isString(obj) //should be false, but true
    
  • 4

    如果您在node.js环境中工作,则可以在utils中使用内置函数isString .

    const util = require('util');
    if (util.isString(myVar)) {}
    

    编辑:正如@Jehy所提到的,自v4以来已弃用 .

  • 1557

    我喜欢使用这个简单的解决方案:

    var myString = "test";
    if(myString.constructor === String)
    {
         //It's a string
    }
    
  • 7

    一个简单的解决方案是:

    var x = "hello"
    
    if(x === x.toString(){
    // it's a string 
    }else{
    // it isn't
    }
    
  • 3

    取自lodash:

    function isString(val) {
       return typeof val === 'string' || ((!!val && typeof val === 'object') && Object.prototype.toString.call(val) === '[object String]');
    }
    
    console.log(isString('hello world!')); // true
    console.log(isString(new String('hello world'))); // true
    
  • 4

    我建议使用 jQuerylodash/Underscore 中的内置函数 . 它们使用起来更简单,更易于阅读 .

    这两个函数都将处理DRAX提到的情况......也就是说,它们都检查(A)变量是字符串文字还是(B)它是String对象的实例 . 在任何一种情况下,这些函数都正确地将值标识为字符串 .

    lodash / Underscore.js

    if(_.isString(myVar))
       //it's a string
    else
       //it's something else
    

    jQuery

    if($.type(myVar) === "string")
       //it's a string
    else
       //it's something else
    

    有关详细信息,请参阅lodash Documentation for _.isString() .

    有关详细信息,请参阅jQuery Documentation for $.type() .

  • 30

    这是性能重要的一个很好的例子:

    如果没有正确完成,做一些像字符串测试一样简单的事情可能会很昂贵 .

    例如,如果我想编写一个函数来测试某些东西是否为字符串,我可以通过以下两种方式之一来完成:

    1) const isString = str => (Object.prototype.toString.call(str) === '[object String]');

    2) const isString = str => ((typeof str === 'string') || (str instanceof String));

    这两个都很直接,所以可能会影响性能?一般来说,函数调用可能很昂贵,特别是如果你不知道里面发生了什么 . 在第一个示例中,有一个对Object的toString方法的函数调用 . 在第二个示例中,没有函数调用,因为typeof和instanceof是运算符 . 运算符明显快于函数调用 .

    测试性能时,示例1比示例2慢79%!

    看测试:https://jsperf.com/isstringtype

  • 3

    您可以使用 typeof 运算符:

    var booleanValue = true; 
    var numericalValue = 354;
    var stringValue = "This is a String";
    var stringObject = new String( "This is a String Object" );
    alert(typeof booleanValue) // displays "boolean"
    alert(typeof numericalValue) // displays "number"
    alert(typeof stringValue) // displays "string"
    alert(typeof stringObject) // displays "object"
    

    this webpage中的示例 . (虽然稍微修改了例子) .

    在使用 new String() 创建的字符串的情况下,这将无法正常工作,但这很少用于[1] [2] . 如果您愿意,请参阅其他答案,了解如何处理这些问题 .


  • 8
    function isString (obj) {
      return (Object.prototype.toString.call(obj) === '[object String]');
    }
    

    我在这看到:

    http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/

  • 5

    这对我有用:

    if (typeof myVar === 'string' || myVar instanceof String)
    // it's a string
    else
    // it's something else
    
  • 1210

    以下方法将检查是否有任何变量是字符串( including variables that do not exist ) .

    const is_string = value => {
        try {
            return typeof value() === 'string';
        } catch ( error ) {
            return false;
        }
    };
    
    let example = 'Hello, world!';
    
    console.log( is_string( () => example ) );                 // true
    console.log( is_string( () => variable_doesnt_exist ) );   // false
    
  • -1

    由于有580人投票给出了错误答案,800人投票赞成了一个有效但霰弹枪式的答案,我认为以一种每个人都能理解的简单形式重新回答我的答案是值得的 .

    function isString(x) {
      return Object.prototype.toString.call(x) === "[object String]"
    }
    

    或者,内联(我有一个UltiSnip设置):

    Object.prototype.toString.call(myVar) === "[object String]"
    

    仅供参考,Pablo Santa Cruz的回答是错误的,因为 typeof new String("string")object

    DRAX的答案是准确和实用的,应该是正确的答案(因为Pablo Santa Cruz绝对是错误的,我不会反对普遍的投票 . )

    但是,这个答案也是绝对正确的,实际上是最好的答案(可能除了建议使用lodash / underscore) . 免责声明:我为lodash 4代码库做出了贡献 .

    我的原始答案(显然飞越了很多脑袋)如下:

    我从underscore.js转码了这个:

    ['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'].forEach( 
        function(name) { 
            window['is' + name] = function(obj) {
                  return toString.call(obj) == '[object ' + name + ']';
        }; 
    });
    

    那将定义isString,isNumber等 .


    在Node.js中,这可以作为模块实现:

    module.exports = [
      'Arguments', 
      'Function', 
      'String', 
      'Number', 
      'Date', 
      'RegExp'
    ].reduce( (obj, name) => {
      obj[ 'is' + name ] = x => toString.call(x) == '[object ' + name + ']';
      return obj;
    }, {});
    
  • 1

    最好的办法:

    var s = 'String';
    var a = [1,2,3];
    var o = {key: 'val'};
    
    (s.constructor === String) && console.log('its a string');
    (a.constructor === Array) && console.log('its an array');
    (o.constructor === Object) && console.log('its an object');
    (o.constructor === Number || s.constructor === Boolean) && console.log('this won\'t run');
    

    这些中的每一个都是通过其适当的类函数构造的,如“new Object()”等 .

    此外,鸭子打字:“如果它看起来像一只鸭子,像鸭子一样走路,闻起来像一只鸭子 - 它必须是一个数组”意思,检查它的属性 .

    希望这可以帮助 .

    编辑; 2016年12月5日

    请记住,您也可以始终使用方法组合 . 以下是使用typeof的内联动作映射的示例:

    var type = { 'number': Math.sqrt.bind(Math), ... }[ typeof datum ];
    

    这是使用内联映射的更“真实世界”示例:

    function is(datum) {
        var isnt = !{ null: true, undefined: true, '': true, false: false, 0: false }[ datum ];
        return !isnt;
    }
    console.log( is(0), is(false), is(undefined), ... );  // >> true true false
    

    此函数将使用[custom] "type-casting" - 而不是"type-/-value-mapping" - 来确定变量是否实际为"exists" . 现在你可以在 null0 之间拆分那个讨厌的头发!

    很多时候你甚至不关心它的类型 . 避免打字的另一种方法是组合Duck-Type集:

    this.id = "998";  // use a number or a string-equivalent
    function get(id) {
        if (!id || !id.toString) return;
        if (id.toString() === this.id.toString()) http( id || +this.id );
        // if (+id === +this.id) ...;
    }
    

    Number.prototype and String.prototype 都有一个 .toString() method . 你只是确保数字的字符串等价物是相同的,然后你确保将其作为 Number 传递给 http 函数 . 换句话说,我们甚至不关心它的类型 .

    希望能给你更多的工作:)

  • 112

    我'm not sure if you mean knowing if it'是一个类型 string ,无论其内容如何,或者它的内容是数字还是字符串,无论其类型如何 .

    因此,要知道它的类型是否为字符串,那已经得到了回答 .
    但要根据其内容知道它的字符串或数字,我会用这个:

    function isNumber(item) {
        return (parseInt(item) + '') === item;
    }
    

    并举例说明:

    isNumber(123);   //true
    isNumber('123'); //true
    isNumber('123a');//false
    isNumber('');    //false
    
  • 76
    var a = new String('')
    var b = ''
    var c = []
    
    function isString(x) {
      return x !== null && x !== undefined && x.constructor === String
    }
    
    console.log(isString(a))
    console.log(isString(b))
    console.log(isString(c))
    

相关问题