美文网首页
辨别类型、判断对象属性是否存在

辨别类型、判断对象属性是否存在

作者: locky丶 | 来源:发表于2019-04-28 12:14 被阅读0次

辨别类型

javaScript目前共有7种类型,number、string、undefined、null、boolean、object、symbol。
Array 和function 是object的一个子类型。

/*===== 辨别类型 =====*/
console.log(typeof 42 === "number") // true
console.log(typeof '42' === "string") // true
console.log(typeof undefined === "undefined") // true
console.log(typeof true === "boolean") // true
console.log(typeof {} === "object") // true
console.log(typeof Symbol() === "symbol") // true

/*===== 特殊类型 (空值、数组、函数) =====*/
console.log(typeof null === "object") // true -- null为object是个bug
console.log(typeof [1, 2, 3] === "object") // true 
console.log(typeof
    function doSomething(a, b) {} === "function") // true
// 函数的属性
function doSomething(a, b) {}
console.log(doSomething.length) // 2

辨别空值的方法

var a = null
// 方法1 判断a为空并且是对象
console.log(!a && typeof a === "object") // true
// 方法2 跨原型链调用toString() (推荐)
console.log(Object.prototype.toString.call(null)) // [object Null]

辨别数组的方法

var myArr = [1, 2, 3]
// 方法1 isPrototypeOf() -- 判断myArr是否在Array的原型链中
console.log(Array.prototype.isPrototypeOf(myArr)) // true 

// 方法2 instanceof 实际是在检测对象的继承关系,不可靠 (不推荐)
// myArr属于Array(Array是JS中的内置构造函数)
// 此方法虽然可用,但难于理解,并且会有异常情况产生错误判断
console.log(myArr instanceof Array) // true 

// 方法3 跨原型链调用toString() (推荐)
console.log(Object.prototype.toString.call(myArr)) // [object Array]
console.log(Object.prototype.toString.call(myArr).match(/^\[object\s(.*)\]$/)[1] === 'Array') // true

// 方法4 Array.isArray(obj) (推荐) 
// 此方法属于ES5的范畴,如需旧浏览器支持,需要做兼容处理
console.log(Array.isArray(myArr)) // true

// 方法5 constructor构造器属性
console.log(myArr.constructor == Array) // true

写个跨原型链调用toString()获得object实际类型的函数

var money = null
var skillArr = ['js', 'css', 'html']

function getObjType(obj, objType) {
    return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1] === objType
}
console.log(getObjType(money, 'Null')) // true
console.log(getObjType(skillArr, 'Array')) // true

判断某个属性是否存在于某个对象中

function Animal() {} //定义Animal构造函数
Animal.prototype = { //定义Animal原型
    species: "动物",
    say: function () {
        console.log('i can say word')
    }
}
var cat = new Animal()

var MyAnimal = {
    species: '动物',
    say: function () {
        console.log('i can say word')
    }
}

// 方法1 hasOwnProperty()
console.log(Animal.hasOwnProperty('species')) // false -- 不是自有属性
console.log(MyAnimal.hasOwnProperty('species')) // true -- 是自有属性
// 方法2 in
console.log('species' in cat) // true -- 包含该属性,可以非自有

辨别非数字

var a =2
Number.isNaN(a) // false

判断两个值绝对相等

var a = 2/"foo"  // NaN
var b = -3*0   // -0

Object.is(a, NaN)  // true
Object.is(b, -0)   // true
Object.is(b, 0)   // false

相关文章

网友评论

      本文标题:辨别类型、判断对象属性是否存在

      本文链接:https://www.haomeiwen.com/subject/wrhdnqtx.html