On Mon, Jul 19, 2010 at 08:21, Fritz Zaucker <[email protected]> wrote:
> Hi Martin,
>
> I understand. In Perl there isn't any order in hashes (associative arrays)
> either:
>
> foreach my $key (keys %hash) {
> print "$key\n";
> }
>
> does not give you any particular order.
>
> Therefore you do
>
> foreach my $key (sort keys %hash) {
> print "$key\n";
> }
>
> (assuming you want alphabetical order, for numerical order you'd have to
> specify a sort routine, similar to what sort() in JS does).
>
> Note, the sorting is done by sorting the indices to the hash (called keys
> in
> Perl).
>
There is no standard function or methodology for easily obtaining all of the
keys of an object in JavaScript. You can do the following if you want:
var sortedKeys = [ ];
for (var key in hash)
{
sortedKeys.push(key);
}
sortedKeys.sort();
Now you can iterate through the sorted keys array to access the values in
key-sorted order:
for (var i = 0; i < sortedKeys.length; i++)
{
console.log("The hash of " + sortedKeys[i] + " is " +
hash[sortedKeys[i]]);
}
It's a bit messy, but for those cases where you really need it, it can be
done. You might also consider creating a class to make this easier:
qx.Class.define("custom.Hash",
{
extend : qx.core.Object,
construct : function()
{
this.base(arguments);
// Create an array to keep the keys for quick access or sorting
this.__keys = [ ];
// The place to keep the values, per key
this.__values = { };
},
members :
{
put : function(key, value)
{
// Does this key already exist?
if (this.__values[key] === undefined)
{
// Nope. Add its key to the key list
this.__keys.push(key);
}
// Save the value
this.__values[key] = value;
},
get : function(key)
{
// Return the value corresponding to the given key
return this.__values[key];
},
remove : function(key)
{
// Remove the key from the keys array
qx.lang.Array.remove(this.__keys, key);
// Remove the member from the values map
delete this.__values[key];
},
getSortedKeys : function()
{
// Make a copy of the keys so the user doesn't screw with ours
var keys = qx.lang.Array.clone(this.__keys);
// Sort the keys
keys.sort();
// Give 'em what they came for!
return keys;
}
}
});
// Create a hash table
var hash = new custom.Hash();
hash.put("xyzzy", "magic word 1");
hash.put("abracadabra", "magic word 2");
hash.put("crutiatus", "magic word 3");
// Retrieve the values in key-sorted order
var sortedKeys = hash.getSortedKeys();
for (var i = 0; i < sortedKeys.length; i++)
{
var key = sortedKeys[i];
console.log("key=" + key + ", value=" + hash.get(key));
}
Derrell
------------------------------------------------------------------------------
This SF.net email is sponsored by Sprint
What will you do first with EVO, the first 4G phone?
Visit sprint.com/first -- http://p.sf.net/sfu/sprint-com-first
_______________________________________________
qooxdoo-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/qooxdoo-devel