View Full Version : Arrays - stumped
ahmed
August 17th, 2003, 02:55 PM
ahmed = []
ahmed["a"] = "sdf"
ahmed["b"] = "asd"
trace(ahmed.length) // outputs 0
ahmed = []
ahmed[0] = "sdf"
ahmed[1] = "asd"
trace(ahmed.length) // outputs 2I got two questions:
a) Why does the first piece trace 0 instead of 2?
b) How would i loop through an array where the indexes are literal (not numbers)
any help would be appreciated :)
senocular
August 17th, 2003, 03:03 PM
arrays (lengths) are number based. :-\
claudio
August 17th, 2003, 03:11 PM
Ahmed, in the first case you are using associative array.
ahmed = []
ahmed["a"] = "sdf"
ahmed["b"] = "asd"
trace(ahmed["a"]) // outputs sdfI think you cannot retrieve its length since associative array isnt based on index numbers.
thoriphes
August 17th, 2003, 03:13 PM
I think he's trying to do enumeration.
Voetsjoeba
August 17th, 2003, 03:14 PM
ahmed = [{a:"sdf",c:"whatever"},{b:"afd"}]
trace(ahmed[0].a) // outputs sdf
trace(ahmed[0].c) // outputs whatever
trace(ahmed[1].b) // outputs afd
trace(ahmed.length) // outputs 2
ahmed = []
ahmed["a"] = "sdf"
ahmed["b"] = "asd"
trace(ahmed["a"]) // outputs sdf
ahmed = []
ahmed[0] = "sdf"
ahmed[1] = "asd"
trace(ahmed.length) // outputs 2
I didn't manage to get the length of the array using "a" and "b", since arrays are number based, but if you want to use letters at all costs, you could use the above using objects. This is basically similar to nested arrays, only I'm using objects.
1)What sen said :P
2) What sen is about to say :P:P
senocular
August 17th, 2003, 03:20 PM
if you want, you could always make your own method for checking that
Object.prototype.addProperty("propertyNum",function(){
var L = 0;
for (var i in this) L += this.hasOwnProperty(i);
return L;
},null);
ahmed = []
ahmed["a"] = "sdf";
ahmed["b"] = "asd";
ahmed[0] = "sdf";
ahmed[1] = "asd";
trace(ahmed.length) // outputs 2
trace(ahmed.propertyNum) // outputs 4
ahmed
August 17th, 2003, 03:52 PM
thanks for the proto sen :)
I just realized that I can for..in-loop through the associative array, that i think solves it :)
Powered by vBulletin® Version 4.1.10 Copyright © 2012 vBulletin Solutions, Inc. All rights reserved.