What does [literal] in [array/object] mean?
What does the following syntax mean:
1 in [1,2,3,5]
I know it doesn't search for 1 in the array. But what does it do?
I've seen it used in loops:
for (var i in testArray)
{
}
But have also seen this used by itself. Does it mean c开发者_如何转开发heck if the literal is a valid index in the array or object that is the other operand?
Very simply, it's an object property search:
print ('a' in {'a':1, 'b': 2}); // true
print ('c' in {'a':1, 'b': 2}); // false
Live demo.
This is subtly different to the similar use of in
in for
loops.
Also note that it should not be used with arrays, although this is a common error to make.
It is unspecified what properties besides numeric keys make up the internals of an array, so you should stick to the Array API (e.g. indexOf) if you're using Arrays, otherwise you'll end up with behaviour that you may not expect:
print ('length' in [1,2,3,4]); // true
literalin
object means: "Get a property literal from object."
When used in a loop, the engine will try to access all properties of the object.
1 in [1,2,3,4]
doesn't check for an occurence of an element with a value of 1
, but it checks whether element 1 (array[1]
) exists or not.
It looks like a cheap way not to use a traditional for
loop for each item in the array.
Your 2nd example is a for-each loop. It doesn't have the literal 1
(one).
It's used to iterate JavaScript objects.
This loop will iterate through each "key" in the object.
Its common usage is iterate through such objects:
var Car = { color: "blue", price: 20000 };
for (var key in Car)
console.log("Propery " + key + " of Car is: " + Car[key]);
Live test case - check Chrome/Firefox JavaScript console to see the output.
When used for plain arrays, each "key" will be the index.. for example:
var nums = [20, 15, 30]
for (var key in nums)
console.log("Propery " + key + " of array is: " + nums[key]);
Will show the keys as 0, 1 and 2. Updated fiddle for such case.
'in' operator returns true if specified property exists in specified object; used in a loop it allows you to iterate over all properties of the object
精彩评论