Please what's the difference between the two items in JavaScript?

时间:2016-03-02 10:50:34

标签: javascript object

Please am confused, what's the difference between the two items? I want to apply a solution to this code i'm writing here's the link on plunkr http://plnkr.co/edit/NHS1XYApFEOB2ROUpRSH

Thanks For Helping Out. I'm a total beginner into coding.

var myVariable = {};
Object.defineProperties(myVariable, {
    'newProperty1': {
         value: 'valueOfPropertyOne'
     }
});

and:

var myVariable = [];
Object.defineProperties(myVariable, {
    'newProperty1': {
        value: 'valueOfPropertyOne'
    }
});

1 个答案:

答案 0 :(得分:3)

The difference is that in the first case, you end up with a non-array object because you created it with {} (an object initializer), and in the second case you end up with an array (which is also an object) because you created it with [] (an array initializer). So in the second case, you'll have the magic length property, the various things provided by Array.prototype, etc.

Typically, you would only use an array when you need those array-specific features.

The reason you can define newProperty1 on the array is that arrays are objects, and so you can add properties to them. In fact, normal arrays like the one you're using in your second example aren't really arrays at all (links to a post on my anemic little blog), they're just objects backed by Array.prototype with a couple of special features.