我如何确定一个对象x是否具有定义的属性y,而不管x.y的值是多少?
我正在使用
if (typeof(x.y) !== 'undefined')
但这似乎有点笨拙。有没有更好的办法?
我如何确定一个对象x是否具有定义的属性y,而不管x.y的值是多少?
我正在使用
if (typeof(x.y) !== 'undefined')
但这似乎有点笨拙。有没有更好的办法?
当前回答
ES6 +:
ES6+有一个新功能,你可以像下面这样检查:
if (x?.y)
实际上,解释器检查x的存在,然后调用y,因为在if括号内,强制发生,x?Y转换为布尔值。
其他回答
为什么不简单地:
if (typeof myObject.myProperty == "undefined") alert("myProperty is not defined!");
或者如果你想要一个特定的类型:
if (typeof myObject.myProperty != "string") alert("myProperty has wrong type or does not exist!");
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 }
你可以像这样修剪一下:
if ( x.y !== undefined ) ...
对象具有以下属性:
如果你正在测试对象本身的属性(不是原型链的一部分),你可以使用.hasOwnProperty():
if (x.hasOwnProperty('y')) {
// ......
}
对象或其原型具有一个属性:
您还可以使用in操作符测试继承的属性。
if ('y' in x) {
// ......
}
包括
Object.keys(x).includes('y');
array .prototype.includes()方法确定数组在其条目中是否包含某个值,并根据需要返回true或false。
and
object. keys()返回一个字符串数组,表示给定对象的所有可枚举属性。
. hasownproperty()和ES6+ ?-option -chaining如:if (x?.y)是非常好的2020+选项。