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


当前回答

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

我在这里看到了:

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

其他回答

这是一个很好的例子,说明了为什么性能很重要:

如果做得不正确,对字符串进行测试这样简单的操作可能会很昂贵。

例如,如果我想写一个函数来测试某个东西是否是字符串,我可以用以下两种方法之一:

1) const isString=str=>(Object.pr原型.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

最佳方式:

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

为了扩展@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。

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

我在这里看到了:

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