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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:32:01  来源:igfitidea点击:

What's the equivalent of "has_key" in javascript?

javascriptpython

提问by TIMEX

if dictionary.has_key('school'):

How would you write this in javascript?

你会如何用javascript写这个?

回答by icktoofay

hasOwnProperty:

hasOwnProperty

if(Object.prototype.hasOwnProperty.call(dictionary, key)) {
    // ...

You can also use the inoperator, but sometimes it gives undesirable results:

您还可以使用in运营商,但有时给人意想不到的结果:

console.log('watch' in dictionary); // always true

回答by kay - SE is evil

Either with the inoperator:

要么与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 != undefinedas undefined is not a keyword:

不得使用!= undefinedundefined不是关键字

if(dictionary.school != undefined) { …
if(dictionary.school != undefined) { …

But you can use != nullinstead, which is true for null, undefinedand absent values:

但是你可以使用!= null,而不是,这是真实的nullundefined并没有值:

if(dictionary.school != null) { …

回答by Peter

You may also try:

你也可以试试:

if(dictionary.hasOwnProperty('school'))

The hasOwnPropertymethod will only evaluate to trueif 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)