【发布时间】:2010-09-13 05:19:53
【问题描述】:
如何在 JavaScript 中检查对象是否具有特定属性?
考虑:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
这是最好的方法吗?
【问题讨论】:
-
我用大家的答案写了一个jsperf测试,看看哪个最快:jsperf.com/dictionary-contains-key
-
(对象中的'propertyName')? '属性存在' : '属性不存在'
-
@styfle 感谢 jsperf 测试。
in和hasOwnProperty出来方式对我来说比其他人慢(慢 98%)。我对hasOwnProperty变慢并不感到惊讶,但我对in感到惊讶。 -
有一个新的第 3 阶段提案
Object.hasOwn,它解决了Object.prototype.hasOwnProperty的一些问题。
标签: javascript