js判断对象属性是否存在

使用 hasOwnProperty 方法,该方法返回一个布尔值 true 或 false

obj.hasOwnProperty(prop) 

举例:

const object1 = {};
object1.property1 = 123;

console.log(object1.hasOwnProperty('property1'));
// expected output: true
console.log(object1.hasOwnProperty('property_false'));
// expected output: false

但是这种方法在 Node环境(version12)下有时不可用,提示 没有 hasOwnProperty方法,可使用对象原型链方法:

var data = Object.create(null);
Object.prototype.hasOwnProperty.call(data, 'test_null');

参考链接:
https://stackoverflow.com/questions/16585209/node-js-object-object-has-no-method-hasownproperty

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Author: thinkwei

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注