如何确定变量是字符串还是JavaScript中的其他变量?
当前回答
if (s && typeof s.valueOf() === "string") {
// s is a string
}
既适用于字符串文本let s=“blah”,也适用于对象字符串let s=新字符串('blah')
其他回答
我不确定你的意思是知道它是一个类型字符串而不管它的内容,还是它的内容是一个数字或字符串而不管其类型。所以要知道它的类型是否是字符串,这已经得到了答案。但要根据它的内容知道它是字符串还是数字,我会使用这个:
function isNumber(item) {
return (parseInt(item) + '') === item;
}
例如:
isNumber(123); //true
isNumber('123'); //true
isNumber('123a');//false
isNumber(''); //false
isString()使用可选链接和最新标准检查传递的参数是否为字符串:
const isString = (value) => {
return value?.constructor === String;
}
您可以使用此函数确定任何对象的类型:
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
我还发现这也很好,而且比其他例子要短得多。
if (myVar === myVar + '') {
//its string
} else {
//its something else
}
通过串联空引号,它将值转换为字符串。如果myVar已经是字符串,则If语句成功。
function isString (obj) {
return (Object.prototype.toString.call(obj) === '[object String]');
}
我在这里看到了:
http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
推荐文章
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 将整数转换为字符串,以逗号表示千
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- printf()和puts()在C语言中的区别是什么?
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔
- TypeScript枚举对象数组
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式
- onClick ReactJS调用多个函数