Javascript fun

osfameron on 2005-02-01T14:08:37

OK, I really like Javascript. Most of the reasons to hate Javascript are the incompatibilities between the browsers, and the fact that IE's implementation has broken, laconic error reporting.

In the language, things I don't like include.

  • No multiline strings.
  • the for(x in y) construct applies to Objects and can't be overloaded, so it doesn't do the right thing for arrays and you still need to write for (var i=0; i<arr.length;i++) ad infinitum
  • There's a watch property which is similar to tie-ing writes to an object, but I can't find a similar way to tie reads.
  • + is overloaded to mean string concatenate. To add 2 variables you need to do something like var1 -0 + var2 (subtracting 0, of course, to coerce it into a number, because doing +0 would just append "0" if var1 is a string)


javascript for/in

rjbs on 2005-02-01T14:46:50

The irritating thing, to me, is that it does (sort of) do the right thing for Arrays, but not Array-alikes.

For an array, for/in iterates over indices. Weird, but fine. It's a fair shorthand for a three-part for. The problem is with Array-like objects like, say, nodeList. A node list is supposed to act just like an Array, but for/in will iterate over a nodeList's attributes, not its elements. Argh! JS needs real iterators.

Re:javascript for/in

osfameron on 2005-02-01T15:22:41

Using a ruby-like for method could be the way forward?
Array.prototype.foreach = function(fn) {
  var l = this.length;
  for (var i=0; i<l; i++) {
    fn(this[i])
  }
}

var arr=[1,2,3,4,5];

arr.foreach(function(v) {
  print( v, ' squared is ', v*v, "\n")
});
You could give nodeList'd prototype a different method which does the right thing there. (Not that I've tested - actually, if nodeList is a native code object then adding a javascript prototype method might not do anything at all useful).

Also, note that if you add "foreach", it'll appear as a property in for/in!

Aristotle's idea

broquaint on 2005-02-03T06:14:26

The venerable Aristotle wrote about this recently in his blog where he demonstrates a lightweight iterator class.