function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
•
变量是否定义
"undefined" === typeof 变量名
// 数组里找到并删除
positionsObj.splice(positionsObj.findIndex(v => {
return v.id === target
}), 1);
// 指定位置插入
positionsObj.splice(parseInt(previewPoint.attr("data-prev-id")) + 1, 0, {
x: left,
y: top,
id: lastId
});
Object.prototype.toString.call(obj) === '[object Object]'
//表达式 返回值
typeof undefined 'undefined'
typeof null 'object'
typeof true 'boolean'
typeof 123 'number'
typeof "abc" 'string'
typeof function() {} 'function'
typeof {} 'object'
typeof [] 'object'
var a=''; console.log(!!a)
VM15885:1 false
undefined
var a=null; console.log(!!a)
VM15913:1 false
undefined
var a=undefined; console.log(!!a)
VM15937:1 false
undefined
var a=''; console.log(!a)
VM15952:1 true
undefined
var a=null; console.log(!a)
VM15967:1 true
undefined
var a=undefined; console.log(!a)
VM15989:1 true
其实,js 在底层存储变量的时候,会在变量的机器码的低位1-3位存储其类型信息👉
•
000:对象
•
010:浮点数
•
100:字符串
•
110:布尔
•
1:整数
but, 对于 undefined 和 null 来说,这两个值的信息存储是有点特殊的。
null:所有机器码均为0
undefined:用 −2^30 整数来表示
所以,typeof 在判断 null 的时候就出现问题了,由于 null 的所有机器码均为0,因此直接被当做了对象来看待。
然而用 instanceof 来判断的话👉
null instanceof null // TypeError: Right-hand side of 'instanceof' is not an object
复制代码
null 直接被判断为不是 object,这也是 JavaScript 的历史遗留bug,可以参考typeof。
因此在用 typeof 来判断变量类型的时候,我们需要注意,最好是用 typeof 来判断基本数据类型(包括symbol),避免对 null 的判断。
还有一个不错的判断类型的方法,就是Object.prototype.toString,我们可以利用这个方法来对一个变量的类型来进行比较准确的判断
Object.prototype.toString.call(1) // "[object Number]"
Object.prototype.toString.call('hi') // "[object String]"
Object.prototype.toString.call({a:'hi'}) // "[object Object]"
Object.prototype.toString.call([1,'a']) // "[object Array]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(() => {}) // "[object Function]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(Symbol(1)) // "[object Symbol]"
复制代码
作者:nicole_zhang18970
链接:https://juejin.cn/post/6844903613584654344
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论区