3 ms·
I don't know why the second-top one has so many votes, it's completely wrong. var x = 1; var y = 3; var list = [0,1,2]; x in list; //true y in l
by technoguyrob 18y ago
I don't know why the second-top one has so many votes, it's completely wrong.
var x = 1;
var y = 3;
var list = [0,1,2];
x in list; //true
y in list; //false
1 in list; //true
y in [3,4,5]; //true
That last expression is false. This is because the "in" operator does not check for values in the list; it checks for keys. Try this:
javascript:alert(3 in [3,4,5])
The only things that will be true for "X in [3,4,5]" are 0, 1, and 2 for X (since these are the natural keys for the terms in the array). More specifically, "in" in general checks for members associated with objects (e.g., keys in an array, methods of a class, etc.):
javascript:alert("The setFlag method " + ("setFlag" in {setFlag:function(){}} ? "exists" : "does not exist"))
EDIT: This makes the keyword considerably less useful (since indexOf doesn't work for the Array object in IE--although jQuery has a way around this), although it can be used to replace the less elegant
if (typeof object.method == "undefined")
- wayne 18y agoOther fun 'in' trivia: It looks through the object's entire prototype chain: http://yuiblog.com/blog/2006/09/26/for-in-intrigue/ http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
- johns 18y agoGo post a comment on that answer to clarify it.
- PieSquared 18y agoOh whoa! I never realized I could just type "javascript:..." into the status bar in Firefox and have it run it. That's awesome. (In retrospect, I realize I should've realized it, because I've always known that the javascript links are "javascript:functionCall()" or some such.)