June 14, 2011 at 12:15 PM by Dr. Drang
In the post about Google Maps using the scroll wheel for zooming instead of scrolling, I mentioned that although I knew perfectly well that Google was doing this, I just couldn’t stop myself 1 from trying to scroll that way. Last night, as I was adding a spam detection function to Dr. Twoot, I ran into a similar mental block that I just can’t get around.
This block involves the
x in s operator in Python.
It’s the “sort of” part that always gets me. While
x in s returns True if item
x is in list
s and False if it doesn’t,
inArray(x, s) does something a little different. It returns the index of
x is in
s and returns -1 if
x isn’t in
it won’t do the right thing if
x is the first item of
s. Just as bad, it’ll also do the wrong thing if
x isn’t in
s because -1 is considered true.
There are now three places in the Dr. Twoot code where I use
inArray to test an item’s membership in an array. In every case I have initially used it incorrectly, like the snippet of code above, instead of correctly, like this:
As with my Google Maps scroll wheel confusion, part of the problem certainly lies with jQuery. The name
inArray makes it sound like a function that returns a Boolean. But all languages have their quirks, and I can usually keep them straight. This one, though gets me every time.
indexOf method. Its name is much more indicative of what it does, and what it does is effectively the same as
inArray. I can only answer that I started using
inArray because Internet Explorer didn’t support
indexOf and I wanted my code to work in IE.
That’s not a great answer, I know, because Dr. Twoot is Mac-only—it’s a Fluid SSB—and
indexOf works just fine on Macs. I can only say feebly that’s another mental block of mine. I need some kind of druid dude to lift the veil.