vendredi 11 septembre 2015

Javascript object accessor weirdness

so I've been coming across a weird issue with javascript objects. Maybe it's just a lack of knowledge (relatively newer to JS), or part of the weird world of JS, but here it goes:

Whenever I try to check if an object has some property, ie:

var someObject = {};
var someArray = ['cat', 'cat', 'cat', 'dog', 'dog', 'dog', 'cow', 'horse'];
someArray.some(function(animal, index) {
    if (!someObject[animal]) {
        someObject[animal] = index;
    }
};

now if I'm not mistaken, the expected output of this should be as follows:

someObject = {
    'cat': 0,
    'dog': 3,
    'cow': 6,
    'horse': 7
}

however what I'm getting is:

someObject = {
    'cat': 1,
    'dog': 3,
    'cow': 6,
    'horse': 7
}

wat.

Also, the issue is resolved when I switch to using the following:

someArray.some(function(animal, index) {
     if (!someObject.hasOwnProperty(animal)) {
        someObject[animal] = index;
     }
  });

WAT. Not that it's much an issue since I've figured out the above solution, I'm just curious as to if I'm not understanding how the object[property] feature works? Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire