|
Prev: Ugh
Next: Artificial Intelligence updated 2008 May 4
From: Thomas 'PointedEars' Lahn on 6 May 2008 18:26 Tom Cole wrote: > Javascript arrays are a little tricky in this regards. Yes you can > "name" and Array entry, or more accurately assign a "name" as the key. > The problem is, in my experience, that when store array elements in > this manner, the length of the array is not adjusted. Because you are not storing array elements then, but augment the Array object. > For example this is totally legit: > > var images = new Array(); > images['Massey 2007'] = "ecwp://" + document.location.host + "/massey/ > images/massey/massey_07_fullres.ecw"; > images['Massey 2006'] = "ecwp://" + document.location.host + "/massey/ > images/massey/massey_06_fullres.ecw"; And why not? Array objects are native objects and, some properties with the ReadOnly attribute aside, native objects can be augmented with any number of properties. > However if you call alert(images.length) you will get 0. It helps to use a collection implementation instead. > Of course even if it didn't, this wouldn't help, because you need the key (or > "name") not just the value. And there is no method that I have found > to retrieve the list of keys an array is using. var a = ["x", 42]; a["foo"] = "bar"; var out = []; for (var key in a) { var p = a[key]; var t = typeof p; if (t == "string") { p = '"' + p.replace(/"/g, "\\$&") + '"'; } out.push(key + ": " + t + " = " + p); } // displays the enumerable properties of `a' // and the objects in its prototype chain window.alert(out.join("\n")); Note that this can be useful with a collection implementation; if a collection is not required, then one should use an Object object instead of an Array object. > So...the problem isn't "naming" your array elements, but how do you > remember that list of names so you can later retrieve the values. Provided one does not augment Object.prototype or Array.prototype, it is not as hard to implement as you think. > You will probably need two arrays, one to store the "names" and the > other to store the "values". No, this is not necessary. You can create user-defined objects that are elements of the array instead. PointedEars -- realism: HTML 4.01 Strict evangelism: XHTML 1.0 Strict madness: XHTML 1.1 as application/xhtml+xml -- Bjoern Hoehrmann |