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
 }
3
  • 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) Commented Jul 25, 2014 at 16:10
  • you might want Object.keys(myArray).length, but you should likely use an object instead of an array. Commented Jul 25, 2014 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. Commented Jul 25, 2014 at 16:14

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

6 Comments

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: 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 .
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.
@acrosman the question is a duplicate; there's a fine explanation in the linked question.
@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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.