9

So, why does this result in 0 and how do I find the actual size?

var array = [];
array["foo"] = "bar";
array["bar"] = "foo";

document.write(array.length);
Mantar
  • 2,710
  • 5
  • 23
  • 30

7 Answers7

7

First off, the length is 0 because the number of items in array is 0.

When you do this syntax array["foo"] = "bar" you're creating a property called foo that has a value of bar. The length is still 0 since you have not added anything to the Array, you've just set new properties on the Array

Working version here: http://jsfiddle.net/VyjJD/3/

var array = [];

array["foo"] = "bar";
array["bar"] = "foo";
array.bin = function() { return "bin"; };

array[0] = "bar";
array[1] = "foo";
array[2] = "bin";
array[3] = "bat";

var props = 0;

for (key in array)
    props++;

document.write(array.length + "<br />" 
           + props + "<br />" 
           + (array.foo == array["foo"]) + "<br />" 
           + array.bar + "<br />"
           + array.bin());

Notice that array.length = 4 but props = 7 which is all of the properties and the number of items in the Array.

hunter
  • 62,308
  • 19
  • 113
  • 113
6

Since that is a object, which is comprised of properties, and take the form of key/value pairs (conceptually similar to an associative array, or a hash table) you will have to do something like this:

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

var array = [];
array["foo"] = "bar";
array["bar"] = "foo";

var size = Object.size(array);

Demo: http://jsfiddle.net/gBG34/

karim79
  • 339,989
  • 67
  • 413
  • 406
  • 1
    Or also: Object.prototype.size = function()... And then you can use it like: var size = array.size() – José Leal Jan 07 '11 at 16:57
  • ...or as a plain-old function, and just do `getSize(var);` – karim79 Jan 07 '11 at 16:58
  • 3
    There's no such thing as an associative array in JS. It's an object and just an alternative syntax to access it's properties. Instead of `array["foo"]` you may as well write `array.foo`. That's why the length property doesn't work. He's setting properties on an array object and not adding items to an array. – DanMan Jan 07 '11 at 17:01
  • @DanMan Fair enough, but how do I find how many properties the array has then? – Mantar Jan 07 '11 at 17:03
  • @DanMan - But you can think of it as one. In the same way you can call it a 'hash table'. I'm aware that 'properties' can be accessed using both square bracket and dot notation. – karim79 Jan 07 '11 at 17:04
  • @karim79 - Fine, but since array methods don't work on those properties i think it's wrong to call it an array. @Meke: see the other people's answers. – DanMan Jan 07 '11 at 17:09
  • @José Leal: I'd strongly recommend against extending `Object.prototype` since it affects *every* type of object, and will make `hasOwnPropety` an absolute requirement, completely removing the ability to iterate over other desired `prototype` properties (unless you explicitly test to avoid the `"size"` prototyped property). @karim79's method is much safer. – user113716 Jan 07 '11 at 17:17
  • This is all well and good until you add items to the Array, not properties. Each item in the array counts, too. I guess you'd need to do `size = size - (!!obj.length ? obj.length : 0)` – hunter Jan 07 '11 at 17:18
  • @hunter - Good point. I just assumed that he would want to count Array.push'ed elements too. Thanks for the comment. – karim79 Jan 07 '11 at 17:20
4

You are setting a property on the array, not giving it a new element. Arrays can receive arbitrary properties, just like any other Javascript object. For instance:

var foo = [];
foo.bar = 'foobar';
console.log(foo.bar); // outputs 'foobar'
console.log(foo); // outputs [] -- empty array

To add items to an array, use Array.push:

var foo = [];
foo.push('foobar');
console.log(foo); // outputs ['foobar']

If you want key=>value pairs, use an object instead:

var foo = {};
foo['bar'] = 'foobar';
console.log(foo); // outputs {bar: 'foobar'}
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
1

basically when you do

array["foo"] = "bar"

it just adds some more attributes to the array, which is an object. In javascript, array.foo and array['foo'] means the same.

José Leal
  • 7,989
  • 9
  • 35
  • 54
0

Object.keys(array).length

see this: https://stackoverflow.com/a/13802999/1488217

credits goes to ian

Community
  • 1
  • 1
Zen
  • 382
  • 3
  • 9
0

Maybe I'm being naive (my javascript isn't what it might be), but shouldn't it be something like this:

var array = [];
array[0] = "bar";
array[1] = "foo";
document.write(array.length);
ilivewithian
  • 19,476
  • 19
  • 103
  • 165
0

The actual size is 0 because you did not put any items into array object - this can only be done either by a method (push etc.) or by the means of assigning value to an indexed property (or in constructor).

Sergey Ilinsky
  • 31,255
  • 9
  • 54
  • 56