使用 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