javascript 中“has_key”的等价物是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6687740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the equivalent of "has_key" in javascript?
提问by TIMEX
if dictionary.has_key('school'):
How would you write this in javascript?
你会如何用javascript写这个?
回答by icktoofay
if(Object.prototype.hasOwnProperty.call(dictionary, key)) {
// ...
You can also use the in
operator, but sometimes it gives undesirable results:
您还可以使用的in
运营商,但有时给人意想不到的结果:
console.log('watch' in dictionary); // always true
回答by kay - SE is evil
Either with the in
operator:
要么与in
运营商:
if('school' in dictionary) { …
Or probably supported in more bowsers: hasOwnProperty
或者可能在更多的浏览器中得到支持: hasOwnProperty
if({}.hasOwnProperty.call(dictionary, 'school')) { …
Could be problematic in border cases: typeof
在边境情况下可能会出现问题: typeof
if(typeof(dictionary.school) !== 'undefined') { …
One must not use != undefined
as undefined is not a keyword:
不得使用!= undefined
undefined不是关键字:
if(dictionary.school != undefined) { …
if(dictionary.school != undefined) { …
But you can use != null
instead, which is true for null
, undefined
and absent values:
但是你可以使用!= null
,而不是,这是真实的null
,undefined
并没有值:
if(dictionary.school != null) { …
回答by Peter
You may also try:
你也可以试试:
if(dictionary.hasOwnProperty('school'))
The hasOwnProperty
method will only evaluate to true
if the property is actually on the instance, and not simply inherited from the prototype -- as is the case with in
.
该hasOwnProperty
方法只会评估true
属性是否确实在实例上,而不是简单地从原型继承——就像in
.
For instance, evaluting ('toString' in myObject)
will be true
, while myObject.hasOwnProperty('toString')
will be false
.
例如,评估('toString' in myObject)
将是true
,而myObject.hasOwnProperty('toString')
将是false
。
回答by swalk
The 'in' operator.
“输入”运算符。
if ('school' in dictionary)
回答by kennebec
Or even,
甚至,
if(dictionary.school!=undefined)