>我有一个名为processData的方法,其中我使用以下代码来检查变量的类型
typeof series.dataSource.xName == "string"
jQuery.type(series.dataSource.xName)=="string"
我想知道哪个更快,执行时间更短,整体"类型"需要 55ms 才能执行,我需要优化它
提前致谢
这是你的答案 详见....
使用vanilla JS比jQuery快10-20倍。但是,有几种类型jQuery将提供有关值的更多信息。所以这里有区别:
╔══════════════════════════════════════════════╦════════════════════════════════════════╗
║ jQuery ║ Vanilla ║
╠══════════════════════════════════════════════╬════════════════════════════════════════╣
║ jQuery.type(null) === 'null' ║ typeof null === 'object' ║
║ ║ ║
║ jQuery.type(new Boolean()) === 'boolean' ║ typeof new Boolean() === 'object' ║
║ jQuery.type(Boolean()) === 'boolean' ║ typeof Boolean() === 'object' ║
║ jQuery.type(Object(Boolean())) === 'boolean' ║ typeof Object(Boolean()) === 'object' ║
║ ║
║ Same applies to all other Constructors i.e. same result with/without new/Object() ║
║ ║
║ jQuery.type(new Number(42)) === 'number' ║ typeof new Number(42) === 'object' ║
║ jQuery.type(new String('test')) === 'string' ║ typeof new String('test') === 'object' ║
║ jQuery.type(new Date()) === 'date' ║ typeof new Date() === 'object' ║
║ jQuery.type(new Array()) === 'array' ║ typeof new Array() === 'object' ║
║ jQuery.type(new RegExp()) === 'regexp' ║ typeof new RegExp() === 'object' ║
║ jQuery.type(new Error()) === 'error' ║ typeof new Error() === 'object' ║
║ ║ ║
║ jQuery.type([]) === 'array' ║ typeof [] === 'object' ║
║ jQuery.type(/test/) === 'regexp' ║ typeof /test/ === 'object' ║
║ ║ ║
║ jQuery.type(Symbol()) === 'symbol' ║ typeof Symbol() === 'symbol' (same) ║
║ jQuery.type(Object(Symbol())) === 'symbol' ║ typeof Object(Symbol()) === 'object' ║
╚══════════════════════════════════════════════╩════════════════════════════════════════╝
但是,我建议在 Lodash 中使用专用方法。 例如 _.isUndefined
、_.isString
、_.isNull
、_.isDate
、_.isError
、_.isRegExp
、_.isSymbol
等。
甚至更强大: _.isNil
、_.isNaN
、_.isEmpty
、_.isArrayLike
、_.isObjectLike
、_.isPlainObject
、_.isTypedArray
、_.isSet
、_.isWeakMap
等。