我如何确定一个对象x是否具有定义的属性y,而不管x.y的值是多少?
我正在使用
if (typeof(x.y) !== 'undefined')
但这似乎有点笨拙。有没有更好的办法?
我如何确定一个对象x是否具有定义的属性y,而不管x.y的值是多少?
我正在使用
if (typeof(x.y) !== 'undefined')
但这似乎有点笨拙。有没有更好的办法?
当前回答
为什么不简单地:
if (typeof myObject.myProperty == "undefined") alert("myProperty is not defined!");
或者如果你想要一个特定的类型:
if (typeof myObject.myProperty != "string") alert("myProperty has wrong type or does not exist!");
其他回答
对象具有以下属性:
如果你正在测试对象本身的属性(不是原型链的一部分),你可以使用.hasOwnProperty():
if (x.hasOwnProperty('y')) {
// ......
}
对象或其原型具有一个属性:
您还可以使用in操作符测试继承的属性。
if ('y' in x) {
// ......
}
你可以像这样修剪一下:
if ( x.y !== undefined ) ...
如果你想知道对象物理上是否包含属性@gnarf的答案使用hasOwnProperty将完成工作。
如果你想知道属性是否存在,无论是在对象本身上还是在原型链上,你可以使用in操作符。
if ('prop' in obj) {
// ...
}
Eg.:
var obj = {};
'toString' in obj == true; // inherited from Object.prototype
obj.hasOwnProperty('toString') == false; // doesn't contains it physically
下划线。js或Lodash
if (_.has(x, "y")) ...
:)
const data = [{"b":1,"c":100},{"a":1,"b":1,"c":150},{"a":1,"b":2,"c":100},{"a":2,"b":1,"c":13}]
const result = data.reduce((r, e) => {
r['a'] += (e['a'] ? e['a'] : 0)
r['d'] += (e['b'] ? e['b'] : 0)
r['c'] += (e['c'] ? e['c'] : 0)
return r
}, {'a':0, 'd':0, 'c':0})
console.log(result)
`result` { a: 4, d: 5, c: 363 }