判断JS对象是否拥有某属性

JavaScript023

判断JS对象是否拥有某属性,第1张

第一种,判断js对象中是否有某个属性

var obj = {test : 'test'}

if('test' in obj){

    console.log('yes')

} else {

    console.log('no')

}

第二种,判断js对象本身是否有某个属性(所谓本身有意思是,必须属性是直接在对象上的,而不是通过原型链上找到的。

var Base = function(){}

Base.prototype.test = 'test'

var obj = new Base()

obj.test2 = 'test2'

if('test1' in obj){

    console.log('yes')

} else {

    console.log('no')

}

if(obj.hasOwnProperty('test2')){

    console.log('own')

} else {

    console.log('none')

}

//用in 操作符,可以判断有没有。 用hasOwnProperty来判断在自身有没有。

使用attr()方法来实现

我们可以使用attr()来设置属性,比如设置为只读:

$("#id").attr("disabled",true)

反之,可以通过获取属性值来判断指定属性是否存在

if(typeof($("#id").attr("rel"))=="undefined")

{

//不存在执行

}else{

//存在执行

}