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


当前回答

老实说,我不明白为什么在这种情况下不简单地使用typeof:

if (typeof str === 'string') {
  return 42;
}

是的,它会对对象包装的字符串(例如,新字符串('o'))失败,但这些被广泛认为是一种糟糕的做法,大多数现代开发工具可能会阻止它们的使用。(如果您看到一个,请修复它!)

Object.prototype.toString技巧是所有前端开发人员在其职业生涯中的某一天都会犯下的错误,但不要让它通过巧妙的打磨来欺骗你:只要有人修补Object原型,它就会崩溃:

constisString=thing=>Object.protype.toString.call(thing)=='[objectString]';console.log(isString('fo'));Object.prototype.toString=()=>42;console.log(isString('fo'));

其他回答

以下方法将检查任何变量是否为字符串(包括不存在的变量)。

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

最佳方式:

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函数。换句话说,我们甚至不在乎它的类型。

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

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)

我有一个愚蠢的技巧。但直截了当。

if(maybeAString.toUpperCase)
  weHaveAString(maybeAString)

是的,这远非完美。但这很简单。

这是对我有用的:

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