当前位置: 首页 > Web前端 > JavaScript

JS如何判断一个对象是否包含属性

时间:2023-03-27 01:34:54 JavaScript

1.in运算符语法:propertyinobject;返回值:Boolean//内置对象console.log("PI"inMath);//返回true//自定义对象letcarInfo={make:"Honda",model:"Accord",year:2020};console.log("make"incarInfo);//返回真//in的右操作数必须是一个对象值。例如,您可以指定使用String构造函数创建的字符串,但不能指定字符串文字。letstr=newString("javascript");console.log("length"instr);//returnstruestr="Iisstring";console.log("length"instr);//error:Cannotuse'in'operatortosearchfor'length'in...//只需将属性的值赋给undefined而不删除它,in操作仍将返回trueletcarInfo={make:"Honda",型号:“Accord”,年份:2020};carInfo.make=undefined;console.log(carInfo中的“make”);//返回true//如果一个属性是从原型链继承的,in运算符也将返回true。console.log({}中的“toString”);//Returntrue注意:(1)如果指定属性在指定对象或其原??型链中,则in运算符返回true。(2)可以判断内置对象上的属性。(3)如果使用delete运算符删除属性,则in运算符为删除的属性返回false。(4)如果一个属性的值被赋值给undefined而不删除它,in操作仍然会返回true。(5)字符串的属性也可以判断,但必须是字符串对象newString()创建的字符串。2.Object.hasOwnProperty('Property')语法:Object.hasOwnProperty('Property');返回值:Boolean使用场景:只判断自身属性提示:与原型无关,不会在原型上寻找属性//CustomobjectletcarInfo={make:"Honda",model:"Accord",年份:2020};console.log(obj.hasOwnProperty('make'));//trueconsole.log(obj.hasOwnProperty('model'));//trueconsole.log(obj.hasOwnProperty('price'));//falseconsole.log(obj.hasOwnProperty('toString'));//false//内置对象console.log(Math.hasOwnProperty('PI'));//真3。点(.)或方括号([])语法:obj.property!=undefinedorobj['property']!=undefined返回值:Boolean提示1:可以在原型上查找属性提示2:不能用于对象的属性值存在且属性值未定义的场景。//自定义对象letcarInfo={make:"Honda",model:"Accord",year:2020};console.log(obj.make!=undefined));//trueconsole.log(obj.['model']!=undefined);//trueconsole.log(obj.price!=undefined);//false//内置对象