如何确定变量是字符串还是JavaScript中的其他变量?
当前回答
function isString (obj) {
return (Object.prototype.toString.call(obj) === '[object String]');
}
我在这里看到了:
http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
其他回答
取自lodash:
function isString(val) {
return typeof val === 'string' || ((!!val && typeof val === 'object') && Object.prototype.toString.call(val) === '[object String]');
}
console.log(isString('hello world!')); // true
console.log(isString(new String('hello world'))); // true
从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;
表演
今天2020.09.17我在Chrome v85、Safari v13.1.2和Firefox v80上对MacOs HighSierra 10.13.6进行了测试,以确定所选的解决方案。
后果
对于所有浏览器(以及两个测试用例)
解决方案类型||instanceof(A,I)和x===x+''(H)是快速/最快的解决方案_.isString(lodash-lib)是中等/快速的解决方案B和K是最慢的
更新:2020.11.28我更新了x=123 Chrome列的结果-对于解决方案I,之前可能有一个错误值(=69M太低)-我使用Chrome 86.0重复测试。
细节
我为解决方案执行2个测试用例A.BCDEFGH我JKL
当变量为字符串时,可以在此处运行当变量不是字符串时-可以在此处运行
下面的代码片段显示了解决方案之间的差异
// https://stackoverflow.com/a/9436948/860099函数A(x){return(typeof x==“string”)||(x instanceof string)}// https://stackoverflow.com/a/17772086/860099函数B(x){return Object.pr原型.toString.call(x)==“[对象字符串]”}// https://stackoverflow.com/a/20958909/860099函数C(x){return _.isString(x);}// https://stackoverflow.com/a/20958909/860099函数D(x){return$.type(x)==“string”;}// https://stackoverflow.com/a/16215800/860099函数E(x){返回x?。constructor==字符串;}// https://stackoverflow.com/a/42493631/860099函数F(x){返回x?。charAt!=无效的}// https://stackoverflow.com/a/57443488/860099函数G(x){return字符串(x)==x}// https://stackoverflow.com/a/19057360/860099函数H(x){返回x===x+''}// https://stackoverflow.com/a/4059166/860099函数I(x){返回类型x==“string”}// https://stackoverflow.com/a/28722301/860099函数J(x){返回x===x?。到字符串()}// https://stackoverflow.com/a/58892465/860099函数K(x){返回x&&typeof x.valueOf()==“string”}// https://stackoverflow.com/a/9436948/860099函数L(x){return x字符串实例}// ------------------//演示文稿// ------------------console.log('不同输入的解决方案结果\n\n');console.log(“'abc'Str‘‘‘‘1‘‘0‘1 0{}〔〕true false null undef”);let tests=['abc',new String(“abc”),'','','1','0',1,0,{},[],true,false,null,undefined];[A,B,C,D,E,F,G,H,I,J,K,L]映射(F=>{控制台日志(`${f.name}`+测试.map(v=>(1*!!f(v))).join``)})<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><script src=“https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js“integrity=”sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==“crossrorigin=”匿名“></script>此shippet只显示性能测试中使用的函数,而不执行测试本身!
下面是铬的示例结果
您可以使用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 (s && typeof s.valueOf() === "string") {
// s is a string
}
既适用于字符串文本let s=“blah”,也适用于对象字符串let s=新字符串('blah')
推荐文章
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 将整数转换为字符串,以逗号表示千
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- printf()和puts()在C语言中的区别是什么?
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔
- TypeScript枚举对象数组
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式
- onClick ReactJS调用多个函数