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


当前回答

Typechecker助手:

function isFromType(variable, type){
  if (typeof type == 'string') res = (typeof variable == type.toLowerCase())
  else res = (variable.constructor == type)
  return res
}

用法:

isFromType('cs', 'string') //true
isFromType('cs', String) //true
isFromType(['cs'], Array) //true
isFromType(['cs'], 'object') //false

此外,如果您希望它是递归的(像作为对象的数组),可以使用instanceof。

(['cs']对象实例//true)

其他回答

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

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

它还将考虑null和未定义的类型,并将处理非字符串类型,例如0。

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

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

从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;

最佳方式:

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()”等。

此外,鸭子打字:“如果它看起来像鸭子,走路像鸭子,闻起来像鸭子,那一定是一个阵列”意思是,检查它的财产。

希望这有帮助。

编辑12/05/2016

记住,你也可以使用各种方法的组合。以下是使用类型为的内联操作映射的示例:

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]“类型转换”,而不是“类型-/-值映射”,来确定变量是否实际“存在”。现在,你可以在0和0之间分割那讨厌的头发了!

很多时候你甚至不在乎它的类型。另一种避免键入的方法是组合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和String.prototype都有.toString()方法。您只需确保与数字等效的字符串相同,然后确保将其作为数字传递给http函数。换句话说,我们甚至不在乎它的类型。

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

您可以使用此函数确定任何对象的类型:

var type = function(obj) {
    return Object.prototype.toString.apply(obj).replace(/\[object (.+)\]/i, '$1').toLowerCase();
};

要检查变量是否为字符串,请执行以下操作:

type('my string') === 'string' //true
type(new String('my string')) === 'string' //true
type(`my string`) === 'string' //true
type(12345) === 'string' //false
type({}) === 'string' // false

https://codepen.io/patodiblasi/pen/NQXPwY?editors=0012

要检查其他类型:

type(null) //null
type(undefined) //undefined
type([]) //array
type({}) //object
type(function() {}) //function
type(123) //number
type(new Number(123)) //number
type(/some_regex/) //regexp
type(Symbol("foo")) //symbol