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)
精彩评论