2

I'm having a hard time understanding this code. Could someone try to explain why an array can have elements and 0 length?

var myArray = [];
myArray["hello"] = 4;
myArray["world"] = 65;
$('#btn').on('click',function() {
    console.log(myArray.length); // Prints 0
    console.log(myArray); // Prints [hello: 4, world: 65]
    console.log(myArray.length); // Prints 0
 }
Sebas
  • 21,192
  • 9
  • 55
  • 109
iveqy
  • 19,951
  • 1
  • 15
  • 20
  • this is not asynchronous, and you're using a framework hidding to you 80% of the fun of javascript. So, please don't forget it in your tags (I added it for you) – Sebas Jul 25 '14 at 16:10
  • you might want Object.keys(myArray).length, but you should likely use an object instead of an array. – dandavis Jul 25 '14 at 16:11
  • Length only adds numerically indexed properties, you're using the `Array` in this example as a dictionary. If you want to loop through the `Array`, you could put the `String` and `Number` into an `Object` and insert that into the `Array`. – deadboy Jul 25 '14 at 16:14

1 Answers1

4

The .length property only pertains to numerically-indexed properties.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 2
    No offense, @Pointy but, although true, this isn't really the answer to the question. What he's done here is instantiate a new array object, then add properties to that object named `hello` and `world`. He's setting properties of the array *object*, not elements of the array itself. – Grinn Jul 25 '14 at 16:15
  • 1
    @grinn: FWIW, array elements are so properties of the object. Every property with a numerical, positive 32bit ( or so) property name is considered to be an element . – Felix Kling Jul 25 '14 at 16:31
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – acrosman Jul 25 '14 at 16:59
  • @acrosman the question is a duplicate; there's a fine explanation in the linked question. – Pointy Jul 25 '14 at 17:10
  • @Grinn yes, as Felix Kling notes there really are no semantic differences between numerically-indexed properties and string-indexed properties; indeed, the numerically-indexed properties are really strings too! The `.length` property reflects an internal *interpretation* of the named properties, and those semantics are based on the properties whose names look like non-negative integers. – Pointy Jul 25 '14 at 17:12
  • Thanks @FelixKling and Pointy. I learned something new today! Here's a demonstration of what they're referring to, for those interested: http://codepen.io/grinn/pen/Lbzjc – Grinn Jul 28 '14 at 13:52