Is there any way to create an array-like object in JavaScript, without using the built-in array? I'm specifically concerned with behavior like this:
var sup = new Array(5);
//sup.length here is 0
sup[0] = 'z3ero';
//sup.length here is 1
sup[1] = 'o3ne';
//sup.length here is 2
sup[4] = 'f3our';
//sup.length here is 5
The particular behavior I'm looking at here is that sup.length changes without any methods being called. I understand from this question that the [] operator is overloaded in the case of arrays, and this accounts for this behavior. Is there a pure-javascript way to duplicate this behavior, or is the language not flexible enough for that?
According to the Mozilla docs, values returned by regex also do funky things with this index. Is this possible with plain javascript?
-
Sure, you can replicate almost any data structure in JavaScript, all the basic building blocks are there. What you'll end up will be slower and less intuitive however.
But why not just use push/pop ?
Claudiu : this is more a theoretical question about the limits of javascript than anything practical =P. i think my answer is that you can't do this. -
Mostly you don't need a predefined index-size for arrays in javascript, you can just do:
var sup = []; //Shorthand for an empty array //sup.length is 0 sup.push(1); //Adds an item to the array (You don't need to keep track of index-sizes) //sup.length is 1 sup.push(2); //sup.length is 2 sup.push(4); //sup.length is 3 //sup is [1, 2, 4]
finpingvin : BTW, to answer your specific question more; An custom object that keeps better track on array-indices, if they are important for your cause, perhaps would store an internal array and getter/setter methods for this. The object could fill empty indices with 'null' to represent array.length better. -
[] operator is the native way to access to object properties. It is not available in the language to override in order to change its behaviour.
If what you want is return computed values on the [] operator, you cannot do that in JavaScript since the language does not support the concept of computed property. The only solution is to use a method that will work the same as the [] operator.
MyClass.prototype.getItem = function(index) { return { name: 'Item' + index, value: 2 * index }; }
If what you want is have the same behaviour as a native Array in your class, it is always possible to use native Array methods directly on your class. Internally, your class will store data just like a native array does but will keep its class state. jQuery does that to make the jQuery class have an array behaviour while retaining its methods.
MyClass.prototype.addItem = function(item) { // Will add "item" in "this" as if it was a native array // it will then be accessible using the [] operator Array.prototype.push.call(this, item); }
Claudiu : thank you - this is the kind of answer i was looking to get. -
If you're concerned about performance with your sparse array (though you probably shouldn't be) and wanted to ensure that the structure was only as long as the elements you handed it, you could do this:
var sup = []; sup['0'] = 'z3ero'; sup['1'] = 'o3ne'; sup['4'] = 'f3our'; //sup now contains 3 entries
Again, it's worth noting that you won't likely see any performance gain by doing this. I suspect that Javascript already handles sparse arrays quite nicely, thank you very much.
Claudiu : I believe your code is actually exactly equivalent to my code =P. [] is a literal for "new Array()", and sup[0] and sup['0'] behave identically.Claudiu : oh sorry, i didn't see that you didn't have the initial index set up.Jason Kester : Arrays and Hashtables (and thus, Objects) are all closely related in Javascript, and there's not much distinction between them. An array with string keys behaves like a Hashtable, so in the example above it wouldn't pad itself out with values between 1 and 4. -
Yes, you can subclass an array into an arraylike object easily in JavaScript:
var ArrayLike = function() {}; ArrayLike.prototype = []; ArrayLike.prototype.shuffle = // ... and so on ...
You can then instantiate new array like objects:
var cards = new Arraylike; cards.push('ace of spades', 'two of spades', 'three of spades', ... cards.shuffle();
Unfortunately, this does not work in MSIE. It doesn't keep track of the
length
property. Which rather deflates the whole thing.The problem in more detail on Dean Edwards' How To Subclass The JavaScript Array Object. It later turned out that his workaround wasn't safe as some popup blockers will prevent it.
Matt Kantor : There are some alternative workarounds in the comments of Dean's post that seem to work pretty well (except for some performance issues).Matt Kantor : This one in particular looks interesting: http://webreflection.blogspot.com/2008/03/sorry-dean-but-i-subclassed-array-again.html -
The answer is: there's no way as of now. The array behavior is defined in ECMA-262 as behaving this way, and has explicit algorithms for how to deal with getting and setting of array properties (and not generic object properties). This somewhat dismays me =(.
-
Is this what you're looking for?
Thing = function() {}; Thing.prototype.__defineGetter__('length', function() { var count = 0; for(property in this) count++; return count - 1; // don't count 'length' itself! }); instance = new Thing; console.log(instance.length); // => 0 instance[0] = {}; console.log(instance.length); // => 1 instance[1] = {}; instance[2] = {}; console.log(instance.length); // => 3 instance[5] = {}; instance.property = {}; instance.property.property = {}; // this shouldn't count console.log(instance.length); // => 5
The only drawback is that 'length' will get iterated over in for..in loops as if it were a property. Too bad there isn't a way to set property attributes (this is one thing I really wish I could do).
Matt Kantor : Admittedly, this would be damn slow for large instances.Claudiu : yep... this is also not a standard yet, and it's not the way arrays are implemented in JS - but good answer, this will work
0 comments:
Post a Comment