简介
JavaScript支持多种数据类型,如字符串、数字、浮点数等。字符串是一个字符的集合,如 "John Doe"。通常情况下,你通过用双引号或单引号括住字符来创建它们。另外,你也可以通过使用new String() 构造函数来制作一个字符串。
let myString = 'John Doe';
let myString2 = new String("John Doe");
在执行特定的操作时,你可能会遇到这样的情况,即要求你在处理一个特定的变量之前验证它是否是一个字符串--以免发生错误。我们将在本文中讨论这种情况。首先,我们将看看如何在JavaScript中检查一个特定的变量是否是字符串,然后向你展示一个使用Lodash库的替代方法。
标准解决方案--使用typeof操作符
在JavaScript中,typeof 操作符是检查任何变量类型的最常用方法。另外,你也可以使用typeof() 方法。
let myString = 'John Doe';
typeof myString; // string
typeof(myString); // string
如果与一个字符串一起使用,typeof 操作符会返回"string" 。让我们创造一个简单的例子来证实这一点。
let myString = "John Doe";
if (typeof myString === "string") {
console.log("This variable is a string");
} else {
console.log("This variable is not a string");
}
的确,myString 是一个字符串。
This variable is a string
注意:即使该变量包含一个用单/双引号包裹的数字,它仍然会被视为一个字符串。
typeof 操作符的一个有趣的问题是,它不能识别使用new String() 构造函数创建的字符串。new 关键字创建了一个新的JavaScript对象,它是String 类型的实例。因此,typeof 操作符不会正确识别使用new String() 构造函数创建的字符串。
let myString = new String('John Doe');
console.log(typeof myString); // "object"
在这种情况下,我们需要使用typeof 操作符,而不是instanceof 操作符--它可以检测到用new String() 构造函数创建的对象是String 类型的实例。
let myString = new String("John Doe");
if (myString instanceof String) {
console.log("This variable is a string");
} else {
console.log("This variable is not a string");
}
由于myString 是一个字符串,这段代码将产生以下输出。
This variable is a string
使用Lodash库
如果你已经在你的项目中使用了Lodash库,那么使用它来检查一个变量是否是字符串是没有坏处的。如果我们在其他方面不需要Lodash,那么绝对没有必要有一个依赖性,但是,如果我们已经有了这个依赖性,我们可以利用 _.isString()方法,如果指定的值是一个字符串基元或一个String 对象,它就会返回true ,这使得它既适合显性创建的字符串,也适合隐性创建的字符串。
let myString = new String("John Doe");
if (_.isString(myString)) {
console.log("This variable is a string");
} else {
console.log("This variable is not a string");
}
输出。
This variable is a string
结论
在这篇文章中,我们已经学会了如何在JavaScript中检查一个变量是否是字符串。此外,我们还学习了如何在Lodash这样的外部库中工作。