JavaScript 使用检查变量是否为字符串
在本文中,我们将使用 JavaScript 检查变量是否为字符串。我们可以通过使用许多方法来检查变量。通过使用 typeof 运算符,可以直接应用于变量名或变量,来检查变量的类型。
以下是我们可以检查变量类型是否为字符串的方法:
- 使用typeof
- 使用instanceof运算符
- 使用Underscore.js _.isString()
方法1:使用typeof
语法:
typeof varName;
- varName:这是变量的名称。
示例: 此示例用于检查变量 boolValue 和 numValue 是否为字符串。
let boolValue = true;
let numValue = 17;
let bool, num;
if (typeof boolValue == "string") {
bool = "is a string";
} else {
bool = "is not a string";
}
if (typeof numValue == "string") {
num = "is a string";
} else {
num = "is not a string";
}
console.log(bool);
console.log(num);
输出
is not a string
is not a string
方法2:使用 instanceof 运算符
JavaScript 中的 instanceof 运算符用于在运行时检查对象的类型。
语法:
let gfg = objectName instanceof objectType
示例:
let variable = new String();
if (variable instanceof String) {
console.log("variable is a string.");
} else {
console.log("variable is not a string.");
}
输出
variable is a string.
方法3:Underscore.js _.isString()
_.isString()函数用于检查给定的对象元素是否为字符串。
语法:
_.isString( object )
示例:
let info = {
Company: 'GeeksforGeeks',
Address: 'Noida',
Contact: '+91 9876543210'
};
console.log(_.isString(info));
let str = 'GeeksforGeeks';
console.log(_.isString(str));
输出:
false
true
极客教程