简体   繁体   中英

Is the hasOwnProperty method in JavaScript case sensitive?

Is hasOwnProperty() method case-sensitive? Is there any other alternative case-insensitive version of hasOwnProperty ?

Yes, it's case sensitive (so obj.hasOwnProperty('x').== obj.hasOwnProperty('X') ) You could extend the Object prototype (some people call that monkey patching ):

Object.prototype.hasOwnPropertyCI = function(prop) {
      return ( function(t) {
         var ret = [];
         for (var l in t){
             if (t.hasOwnProperty(l)){
                 ret.push(l.toLowerCase());
             }
         }
         return ret;
     } )(this)
     .indexOf(prop.toLowerCase()) > -1;
}

More functional:

Object.prototype.hasOwnPropertyCI = function(prop) {
   return Object.keys(this)
          .filter(function (v) {
             return v.toLowerCase() === prop.toLowerCase();
           }).length > 0;
};

Old question is old; but still entirely relevant. I searched for a quick answer to this question as well, and ended up figuring out a good solution before I read this, so I thought I'd share it.

Object.defineProperty(Object, 'hasOwnPropertyCI', {
    enumerable: false,
    value: (keyName) => (
        Object.keys(this).findIndex(
            v => v.toUpperCase() === keyName.toUpperCase()
        ) > -1
    }
});

This resolves to true when keyName exists in the object it's called on:

var MyObject = { "foo": "bar" };
MyObject.hasOwnPropertyCI("foo");

Hope that helps someone else: :D

PS: Personally, my implementation slaps the conditional above into an IF statement, since I won't be using it anywhere else in my application (in addition to the fact that I'm not a huge fan of manipulating native prototypes).

Yes, it's case sensitive, because JavaScript is case sensitive.

There is no alternative built-into the language, but you could roll your own:

function hasOwnPropertyCaseInsensitive(obj, property) {
    var props = [];
    for (var i in obj) if (obj.hasOwnProperty(i)) props.push(i);
    var prop;
    while (prop = props.pop()) if (prop.toLowerCase() === property.toLowerCase()) return true;
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM