How do I check if an object has a property in Java

2018-12-31 02:10发布

How do I check if an object has a property in JavaScript?

Consider:

x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
    //Do this
}

Is that the best way to do it?

标签: javascript
23条回答
步步皆殇っ
2楼-- · 2018-12-31 02:47
if (x.key !== undefined)

Armin Ronacher seems to have already beat me to it, but:

Object.prototype.hasOwnProperty = function(property) {
    return this[property] !== undefined;
};

x = {'key': 1};

if (x.hasOwnProperty('key')) {
    alert('have key!');
}

if (!x.hasOwnProperty('bar')) {
    alert('no bar!');
}

A safer, but slower solution, as pointed out by Konrad Rudolph and Armin Ronacher would be:

Object.prototype.hasOwnProperty = function(property) {
    return typeof this[property] !== 'undefined';
};
查看更多
零度萤火
3楼-- · 2018-12-31 02:51

Let's cut through some confusion here. First, let's simplify by assuming hasOwnProperty already exists; this is true of the vast majority of current browsers in use.

hasOwnProperty returns true if the attribute name that is passed to it has been added to the object. It is entirely independent of the actual value assigned to it which may be exactly undefined.

Hence:

var o = {}
o.x = undefined

var a = o.hasOwnProperty('x')  // a is true
var b = o.x === undefined // b is also true

However:

var o = {}

var a = o.hasOwnProperty('x')  // a is now false
var b = o.x === undefined // b is still true

The problem is what happens when an object in the prototype chain has an attribute with the value of undefined? hasOwnProperty will be false for it, and so will !== undefined. Yet, for..in will still list it in the enumeration.

The bottom line is there is no cross-browser way (since Internet Explorer doesn't expose __prototype__) to determine that a specific identifier has not been attached to an object or anything in its prototype chain.

查看更多
怪性笑人.
4楼-- · 2018-12-31 02:52

With risk of massive downvoting, here is another option for a specific case. :)

If you want to test for a member on an object and want to know if it has been set to something other than:

  • ''
  • false
  • null
  • undefined
  • 0 ...

then you can use:

var foo = {};
foo.bar = "Yes, this is a proper value!";
if (!!foo.bar) {
        // member is set, do something
}
查看更多
旧人旧事旧时光
5楼-- · 2018-12-31 02:52

ECMA Script 6 solution with reflect. Create wrapper like:

/**
Gets an argument from array or object.
The possible outcome:
- If the key exists the value is returned.
- If no key exists the default value is returned.
- If no default value is specified an empty string is returned.
@param obj    The object or array to be searched.
@param key    The name of the property or key.
@param defVal Optional default version of the command-line parameter [default ""]
@return The default value in case of an error else the found parameter.
*/
function getSafeReflectArg( obj, key, defVal) {
   "use strict";
   var retVal = (typeof defVal === 'undefined' ? "" : defVal);
   if ( Reflect.has( obj, key) ) {
       return Reflect.get( obj, key);
   }
   return retVal;
}  // getSafeReflectArg
查看更多
孤独总比滥情好
6楼-- · 2018-12-31 02:53

With Underscore.js or (even better) lodash:

_.has(x, 'key');

Which calls Object.prototype.hasOwnProperty, but (a) is shorter to type, and (b) uses "a safe reference to hasOwnProperty" (i.e. it works even if hasOwnProperty is overwritten).

In particular, lodash defines _.has as:

   function has(object, key) {
      return object ? hasOwnProperty.call(object, key) : false;
   }
   // hasOwnProperty = Object.prototype.hasOwnProperty
查看更多
旧人旧事旧时光
7楼-- · 2018-12-31 02:53

If you are searching for a property, then "NO". You want:

if ('prop' in obj) { }

In general you should not care whether or not the property comes from the prototype or the object.

However, because you used 'key' in your sample code, it looks like you are treating the object as a hash, in which case your answer would make sense. All of the hashes keys would be properties in the object, and you avoid the extra properties contributed by the prototype.

John Resig's answer was very comprehensive, but I thought it wasn't clear. Especially with when to use "'prop' in obj".

查看更多
登录 后发表回答