Friday, July 16, 2010

A String is Not an Array You Lazy Bastard

This one kills me, taking a String and treating it like an Array. How many times have you seen this stupid bit of coding lazyness?

$(this).val().length;

Or another one of my favorites:

$(this).val()[3];

Unless jQuery's val method magically somehow returns an array, your fucking doing it wrong.

This is a String, if you want to use it like an Array, then make it into an Array first. It's easy:

$(this).val().split("")[3];

Now that will work across all browsers, and its way less ambiguous.

We could also use the JavaScript charAt method to do the same thing:

$(this).val().charAt(3);

Which also makes your intentions obvious.

No comments:

Post a Comment