如何确定变量是字符串还是JavaScript中的其他变量?
当前回答
我喜欢使用这个简单的解决方案:
var myString = "test";
if(myString.constructor === String)
{
//It's a string
}
其他回答
从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;
}
只有字符串而没有数字的代码
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);
if (s && typeof s.valueOf() === "string") {
// s is a string
}
既适用于字符串文本let s=“blah”,也适用于对象字符串let s=新字符串('blah')
一种简单快速的测试方法是使用构造函数名称属性。
let x = "abc";
console.log(x.constructor.name === "String"); // true
let y = new String('abc');
console.log(y.constructor.name === "String"); // true
表演