PDA

View Full Version : Array length problem



diegolovison
16 Jun 2010, 5:16 AM
<script>
var DB = new Array();
DB['item1'] = 100;
DB['item2'] = 200;
DB['item3'] = 300;

alert(DB.length);

alert(DB['item1']);
</script>


why DB.length return 0?

mystix
16 Jun 2010, 7:55 AM
because you're putting expando properties on the DB array.
an array in javascript is just another object.

either push() new values onto the array:


DB.push(1);
DB.push(2);
DB.push(3);
alert(DB.length); // alerts 3


or assign elements using numeric indices:


DB[0] = 1;
DB[1] = 2;
DB[2] = 3;
alert(DB.length); // alerts 3

Animal
16 Jun 2010, 7:57 AM
In fact you are not wanting an Array there.

You are wanting an object.



var DB = {}; // this means "new Object()", just as [] means "new Array()"
DB.item1 = 100; // faster if the property names are known, as they are here
DB['item2'] = 200;
DB['item3'] = 300;


There is no (currently standard) way of finding how many properties an object has without iterating through them.

diegolovison
16 Jun 2010, 8:54 AM
if you call


DB.clear();

will return error...


thanks :)

diegolovison
16 Jun 2010, 8:56 AM
expando

sorry, but what is this "expando"?

mystix
16 Jun 2010, 9:02 AM
sorry, but what is this "expando"?

http://stackoverflow.com/questions/2506005/javascript-expando-objects


with regards to your previous post (i.e. DB.clear()), you should explain what you're trying to do so people can actually help you.
1 line of code and 1 statement about the code returning an "error" doesn't really say much.

Animal
16 Jun 2010, 9:28 AM
if you call


DB.clear();

will return error...


thanks :)


Errrrm, you're welcome?

diegolovison
16 Jun 2010, 11:25 AM
I complete what you say... :)

DB in my code ISNT one array.. so when you call the method clear() will return error...

Animal
16 Jun 2010, 11:44 AM
Arrays don't have a clear method either.

You should buy a Javascript book.

Also, refer to https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference

diegolovison
16 Jun 2010, 11:52 AM
:)):)):)):)):)):)):)):)):))

sorry, I searched "clear array" on google, and find that really have one method.. :)):)):)):))

I'm a Java Developer.. sorry for this and thanks to help with my code...

Animal
16 Jun 2010, 11:58 AM
I'm a Java developer. Java arrays don't have a clear method.

Collections do, but not arrays.

"clear array" is not a very good term. "clear javascript array" might offer help.

But to clear a javascript array, you can just set the length property to zero.

diegolovison
16 Jun 2010, 12:01 PM
thanks man ;)