-1

Have a look at the below code:

var a = new Array(); // or just []
a[0] = 0
a['one'] = 1;
a['two'] = 2;
a['three'] = 3;

for (var k in a) {
    if (a.hasOwnProperty(k)) {
        alert('key is: ' + k + ', value is: ' + a[k]);
    }
}
alert(a.length); // 1 is printed

Now i get the following explanation for 1 being printed;

Oddly, the length is reported to be 1, yet four keys are printed. That's because we are manipulating both the array elements and the underlying object.

underlying object ? excuse me , i did't quite understand , can anybody explain please? what is this underlying object ? can anybody emphasis ? please note that my question is't directly why 1 is printed but rather i am asking a slightly wider and difficult question and that is what is the underlying object ?

Found the example HERE

3
  • 5
    length is not the number of elements in an array, it's the value of the highest non-negative integer key+1. arrays are objects. the underlying object refers to non expando (integer) keys which are not included in length. generally, you should put alphabetic properties on a object ({}), not an array ([]), even if javascript lets you tack properties onto about anything, including functions, RegExps, Dates, etc... Commented Nov 20, 2015 at 6:00
  • @dandavis superb thanks ! Commented Nov 20, 2015 at 6:03
  • 1
    and the a.push(77); would make it 2 length with value 77 because your [0] gives it 1 length prior and [13] with a push would have made it 15 length Commented Nov 20, 2015 at 6:08

1 Answer 1

4

The length property of an array is simply the next integer after the biggest integer index in the array.

For example, if you declare the following array:

var arr = [];
arr[1234] = 'Hello world';

Then, arr.length will be equal to 1235.

Adding any object properties to it won't affect it:

arr['one'] = '1';
arr['two'] = '2';
arr['three'] = '3';

console.log(arr.length); // still 1235

Moreover, it is correct to not assign such properties to an array.

It is also important to mention that if you decide to JSON.stringify this array now, you will get:

[null, null, null, null, ... 1250 more nulls ..., "Hello world"]

without one, two, three etc.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.