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);
An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ( [] ). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.
To find the length of an array, use array data member 'length'. 'length' gives the number of elements allocated, not the number inserted. Write a class with a main method that creates an array of 10 integers and totals them up.
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.
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/
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'}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With