如何确定变量是字符串还是JavaScript中的其他变量?
当前回答
isString()使用可选链接和最新标准检查传递的参数是否为字符串:
const isString = (value) => {
return value?.constructor === String;
}
其他回答
您可以使用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建议弃用基本对象包装器。
我有一个愚蠢的技巧。但直截了当。
if(maybeAString.toUpperCase)
weHaveAString(maybeAString)
是的,这远非完美。但这很简单。
编辑:当前的方法是typeof value==“string”。例如:
const str = 'hello';
if (typeof str === 'string') { ... }
自节点v4以来,以下内容已被弃用。
如果您在node.js环境中工作,那么只需在utils中使用内置函数isString即可。
const util = require('util');
if (util.isString(myVar)) {}
从lodash库v4.0.0实现
// getTag.js
const toString = Object.prototype.toString;
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function getTag(value) {
if (value == null) {
return value === undefined
? "[object Undefined]"
: "[object Null]";
}
return toString.call(value);
}
// isString.js
import getTag from "./getTag.js";
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* isString('abc')
* // => true
*
* isString(1)
* // => false
*/
function isString(value) {
const type = typeof value;
return (
type === "string" || (type === "object" &&
value != null &&
!Array.isArray(value) &&
getTag(value) == "[object String]")
);
}
export default isString;
isString()使用可选链接和最新标准检查传递的参数是否为字符串:
const isString = (value) => {
return value?.constructor === String;
}