Array Extras 26

With the upcoming Firefox 1.1 release (and other browsers based on Gecko 1.8) things are starting to move in javascript land. During the early years of javascript a lot happend but then came the ambitious plans ofJS2 and the improvements to js just kind of died away for no reason. It seems Mozilla is finally taking some actions in this field and they’ve added a few very useful methods to Array:

Since not everyone is running nightly builds (or Deer Park alpha 1) I’m now providing these methods for anyone who finds them interesting.

I’ve also added the following useful methods. These greatly benefits from the native implementation of indexOf:

  • contains
  • copy
  • insertAt
  • insertBefore
  • removeAt
  • remove
  • http://me.eae.net Emil

    That indexOf method will prove quite useful.
    Nice to see updates to the JavaScript language (implementation) again.

  • M. Schopman

    I hope to see more improvements in future, according to specifications. I have seen an ECMA specification once (dunno if it was a draft or final) where they talked about full support for private/public/protected/virtual/constructors/destructors/classes etc. Such would really improve the acceptance as Javascript as a real language for fat client development.

  • http://erik.eae.net Erik Arvidsson

    Micha: See the JS2 link in the first paragraph.

  • Geoff Moller

    Many thanks for posting the external implementation. Extremely handy :)

  • http://novemberborn.net/ Mark Wubben

    Thanks for the update. The link to the docs for ‘every’ is broken, though :)

  • http://www.davidflanagan.com David Flanagan

    The functions other than indexOf() and lastIndexOf() are getting moved to Function.prototype instead of Array.prototype.

    See https://bugzilla.mozilla.org/show_bug.cgi?id=304828

  • http://www.davidflanagan.com David Flanagan

    I recently proposed an Array.prototype.append() method at my own blog.
    One of the commenters complained that adding enumerable properties to Array.prototype will break any code that uses for/in on an array.

    This argument is very true for Object.prototype: we really can’t add method there. But I’d never heard it expressed for Array.prototype. It is true that one can use for/in to iterate through the indexes of an array. But does anyone actually do this? If someone does this do they deserve to have their code break?

  • http://www.davidflanagan.com David Flanagan

    I have to keep submitting comments because I love the little popup that appears to show me that my comment has been added at the bottom!

  • Nick Van Weerdenburg

    After the last comment, I need to add a comment.

  • http://erik.eae.net Erik Arvidsson

    David: Thanks for pointing me to that Bugzilla bug. Lot’s of interesting stuff going on there.

    Using a for in loop to loop over an array is incorrect and error prone. It is not too uncommon to see people use it and it shows that people are not aware that it does not really work. See http://erik.eae.net/archives/2005/06/06/22.13.54/#comment-5132

  • Pingback: erik’s weblog » Blog Archive » JS Generics

  • http://n/a Jeoff Hines

    You use the for…in to find the keys in a hash array:
    var a = new Array();
    a["key1"] = “test”;
    a["key2"] = “test”;

    for(var key in a)
    alert(key);

    will show you “key1″ and “key2″. If you add prototypes to Array it will show the names of those functions too and thus break the for/in. I use associative arrays a lot (I like strings) so this is very important to me. If you can think of another way to extract the keys from an associative array then please elucidate because I would love to know! Otherwise, you should leave the built-in objects alone I think.

  • http://erik.eae.net Erik Arvidsson

    Jeoff: Why are you using an Array here? The feature you want is a feature of Object, which Array extends. It is equally correct/incorrect to use a RegExp as an Array.

    Correct?:

    var a = new RegExp();
    a[”key1″] = “test”;
    a[”key2″] = “test”;

    for(var key in a)
    alert(key);

    Correct!:

    var a = {};
    a[”key1″] = “test”;
    a[”key2″] = “test”;

    for(var key in a)
    alert(key);

  • http://www.dandean.com Dan Dean

    Hi Erik,
    Thanks for putting this together and releasing, I find it very useful.

    A note regarding IE5 compatability (yes, I should probably forget about IE5!): I’ve found some good Function.call() and Function.apply() methods at http://www.browserland.org/scripts/dragdrop/. With the addition of these, all of the above methods seem to work in IE5, as long as this is added to the beginning of each that utilize f.call()

    var obj = (obj != null) ? obj : this;

    Do you see any problems with the addition of this?

  • http://erik.eae.net Erik Arvidsson

    Dan: Yes, that would be wrong. If obj is not passed it is supposed to use [[Global]] (or window in a browser context) as the value for this.

    I do not care about JScript 5 (shipped with IE50). It has so many ECMAScript bugs that it is ridicilus and it is holding back development in a lot of scenarios. You would be doing yourself a favor in not supporting it and getting users onto something better and more secure.

    (The same applies to Safari before like the current nightly build and I suggest not supporting anything but the latest version of Safari.)

  • http://www.thomasfrank.se Thomas Frank

    Brilliant! Thanks!

  • http://ecmanaut.blogspot.com/ Johan Sundström

    More of a reflection than suggestion: testing for Array.prototype.forEach and friends this way rather than by way of Array.prototype.hasOwnProperty(‘forEach’) will find Object.prototype.forEach when no Array specific implementation exists. This is probably still often what you want, assuming that the Object prototype internally handles different data types differently in sane manners, but once in a while it might not be.

  • http://whereswalden.com/ Jeff Walden

    Your code for Array.prototype.lastIndexOf has a bug in it: when the second argument is a negative number and the sum of that argument and the array’s length is less than zero, you might erroneously return 0 when searching for the first element in the array. For example:

    [2].lastIndexOf(2, -5)

    …will return 0 with your code, when according to the function’s description it should return -1. The fix should be to replace |Math.max(0, this.length + fromIndex)| with |this.length + fromIndex| in the lastIndexOf implementation.

    Also, don’t bother testing behavior in Firefox, because Firefox has this bug (and an indexOf bug which is a little harder to duplicate). I’m checking whether non-Firefox implementations demonstrate this and the other bug to evaluate how feasible it is to fix this behavior in point releases to stable Firefox versions. (The bug is https://bugzilla.mozilla.org/show_bug.cgi?id=364104 if you’re interested.)

  • http://whereswalden.com/ Jeff Walden

    Actually, let me backtrack for a second — I’m not sure the docs I was referencing were canonical. I’ll get back with more details later…

  • Jan van Casteren

    Thank you for this handy script. One question: is there any reason to have the obj parameter in the copy method?

    See:

    Array.prototype.copy = function (obj) {
    return this.concat();
    };

  • http://erik.eae.net Erik Arvidsson

    Jan: That is just a typo. You should remove that.

  • Pingback: Ajaxian » JavaScript Scripting Essentials

  • Pingback: Scripting Essentials » Professional Web Software Development

  • Pingback: JavaScript Scripting Essentials

  • http://quintessens.wordpress.com Patrick Kwinten

    thanks for the help, I had some problem with using prototype and defining arrays, some how using

    var tagMap= new Array()

    causes that prototype adds other elements to the array :-?

  • Pingback: NCZOnline » Blog Archive » Mozilla’s new Array methods