PDA

View Full Version : Encode "associative" arrays with Ext.encode()



Tim Toady
19 Jul 2010, 5:55 AM
Why does an Ext.encode of an associative array return "[]" when the same exact thing done with an object returns correctly. Isn't a javascript associative array really just an object anyway?



test = [];
test['fred'] = 7;
Ext.encode(test);

test = new Object();
test.fred = 7;
Ext.encode(test);

Animal
19 Jul 2010, 5:57 AM
An Array is different from an Object.

It's an Array, and will always return [item0, item1...] where the items are NUMERICALLY indexed elements.

An object has NAMED properties,

This is Javascript.

Tim Toady
19 Jul 2010, 6:03 AM
Well how can I encode an associative array?

Animal
19 Jul 2010, 6:36 AM
What's that?

Tim Toady
19 Jul 2010, 6:45 AM
Well its not an array. No worries I figured out how to get the behavior I wanted.



bill = 'something';
test = new Object();
test[bill] = 7;
Ext.encode(test);

Animal
19 Jul 2010, 6:46 AM
That's an object



test = {
something: 7
};
Ext.encode(test);

Tim Toady
19 Jul 2010, 6:52 AM
Indeed it is. Perhaps I should have phrased the question as "How do I recreate the behavior of an associative array and encode it"

Tim Toady
19 Jul 2010, 7:47 AM
For anyone who reads this post and is confused as I was, I think I have a much better understanding now:

So using an array as an associative array is a misuse of the array datastructure. the same thing can be done with any datastructure created such as new String(). There are many sites that try to describe it in ways that make it easy to confuse. I was under the misconception that no, they aren't technically arrays, but they are essentially objects. They are in fact arrays with properties thrown onto them that are not meant to be. The best site I found on the subject is located here: http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/