如何确定变量是字符串还是JavaScript中的其他变量?


当前回答

编辑:当前的方法是typeof value==“string”。例如:

const str = 'hello';
if (typeof str === 'string') { ... }

自节点v4以来,以下内容已被弃用。

如果您在node.js环境中工作,那么只需在utils中使用内置函数isString即可。

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

其他回答

一个简单的解决方案是:

var x = "hello"

if(x === x.toString()){
// it's a string 
}else{
// it isn't
}
if (s && typeof s.valueOf() === "string") {
  // s is a string
}

既适用于字符串文本let s=“blah”,也适用于对象字符串let s=新字符串('blah')

从lodash库v4.0.0实现

// getTag.js

const toString = Object.prototype.toString;

/**
 * Gets the `toStringTag` of `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
function getTag(value) {
    if (value == null) {
        return value === undefined 
            ? "[object Undefined]" 
            : "[object Null]";
    }
    return toString.call(value);
}
// isString.js

import getTag from "./getTag.js";

/**
 * Checks if `value` is classified as a `String` primitive or object.
 *
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a string, else `false`.
 * @example
 *
 * isString('abc')
 * // => true
 *
 * isString(1)
 * // => false
 */
function isString(value) {
    const type = typeof value;
    return (
        type === "string" || (type === "object" &&
                              value != null &&
                              !Array.isArray(value) &&
                              getTag(value) == "[object String]")
    );
}

export default isString;

我建议使用jQuery或lodash/Undercore中的内置函数。它们更易于使用和阅读。

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

lodash/Undercore.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

有关详细信息,请参阅_.isString()的lodash文档。

有关详细信息,请参阅$.type()的jQuery文档。

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

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