如何确定变量是字符串还是JavaScript中的其他变量?
当前回答
以下方法将检查任何变量是否为字符串(包括不存在的变量)。
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
其他回答
我建议使用jQuery或lodash/Undercore中的内置函数。它们更易于使用和阅读。
任何一个函数都将处理上述DRAX的情况。。。也就是说,它们都检查(A)变量是字符串文本还是(B)它是string对象的实例。在这两种情况下,这些函数都将值正确地标识为字符串。
lodash/Undercore.js
if(_.isString(myVar))
//it's a string
else
//it's something else
jQuery
if($.type(myVar) === "string")
//it's a string
else
//it's something else
有关详细信息,请参阅_.isString()的lodash文档。
有关详细信息,请参阅$.type()的jQuery文档。
只有字符串而没有数字的代码
isNaN("A") = true;
parseInt("A") = NaN;
isNaN(NaN) = true;
然后我们可以使用isNaN(parseInt())来只包含字符串
let ignoreNumbers=“ad123a4m”;让ign=ignoreNumbers.split(“”).map((ele)=>isNaN(parseInt(ele))?ele:“”).加入(“”);console.log(ign);
最佳方式:
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
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调用多个函数