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


当前回答

由于有580+人投票给了一个错误的答案,而有800+人投票支持一个有效但猎枪式的答案,我认为应该用一种大家都能理解的更简单的形式来重复我的答案。

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

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

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

仅供参考,巴勃罗·圣克鲁斯的答案是错误的,因为新字符串(“String”)的类型是对象

DRAX的答案准确且实用,应该是正确的答案(因为巴勃罗·圣克鲁斯(Pablo Santa Cruz)绝对是错误的,我不会反对全民投票。)

然而,这个答案也绝对正确,实际上是最好的答案(除了使用lodash/下划线的建议)。免责声明:我为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;
}, {});

[编辑]:Object.protype.toString.call(x)也可以在函数和异步函数之间进行描述:

const fn1=()=>new Promise((resolve,reject)=>setTimeout(()=>resolve({}),1000))常量fn2=async()=>({})console.log('fn1',Object.pr原型.toString.call(fn1))console.log('fn2',Object.pr原型.toString.call(fn2))

其他回答

一种简单快速的测试方法是使用构造函数名称属性。

let x = "abc";
console.log(x.constructor.name === "String"); // true

let y = new String('abc');
console.log(y.constructor.name === "String"); // true

表演

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

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

通过串联空引号,它将值转换为字符串。如果myVar已经是字符串,则If语句成功。

您可以使用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"

此网页中的示例。(尽管对示例进行了轻微修改)。

在使用new String()创建字符串的情况下,这不会像预期的那样工作,但这很少被使用,并且建议对[1][2]使用。如果您愿意,请查看其他答案以了解如何处理这些问题。


谷歌JavaScript风格指南说,永远不要使用原始对象包装器。Douglas Crockford建议弃用基本对象包装器。

由于有580+人投票给了一个错误的答案,而有800+人投票支持一个有效但猎枪式的答案,我认为应该用一种大家都能理解的更简单的形式来重复我的答案。

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

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

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

仅供参考,巴勃罗·圣克鲁斯的答案是错误的,因为新字符串(“String”)的类型是对象

DRAX的答案准确且实用,应该是正确的答案(因为巴勃罗·圣克鲁斯(Pablo Santa Cruz)绝对是错误的,我不会反对全民投票。)

然而,这个答案也绝对正确,实际上是最好的答案(除了使用lodash/下划线的建议)。免责声明:我为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;
}, {});

[编辑]:Object.protype.toString.call(x)也可以在函数和异步函数之间进行描述:

const fn1=()=>new Promise((resolve,reject)=>setTimeout(()=>resolve({}),1000))常量fn2=async()=>({})console.log('fn1',Object.pr原型.toString.call(fn1))console.log('fn2',Object.pr原型.toString.call(fn2))

取自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