开发者

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

开发者 https://www.devze.com 2023-03-20 00:00 出处:网络
if dictionary.has_key(\'s开发者_StackOverflowchool\'): How would you write this in javascript?hasOwnProperty:
if dictionary.has_key('s开发者_StackOverflowchool'):

How would you write this in javascript?


hasOwnProperty:

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

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

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


Either with the in operator:

if('school' in dictionary) { …

Or probably supported in more browsers: hasOwnProperty

if({}.hasOwnProperty.call(dictionary, 'school')) { …

Could be problematic in border cases: typeof

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

One must not use != undefined as undefined is not a keyword:

if(dictionary.school != undefined) { …

But you can use != null instead, which is true for null, undefined and absent values:

if(dictionary.school != null) { …


The 'in' operator.

if ('school' in dictionary)


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.

For instance, evaluting ('toString' in myObject) will be true, while myObject.hasOwnProperty('toString') will be false.


Or even,

if(dictionary.school!=undefined)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号