The code is very simple and I would be expecting true however it returns false
var markets = ["AB", "CD"];
console.log("AB" in markets);
The code is very simple and I would be expecting true however it returns false
var markets = ["AB", "CD"];
console.log("AB" in markets);
I think you're meaning if (markets.indexOf('AB') !== -1)
. in
essentially checks if the test is a property of the object, not if an element is contained within the array.
For more information, look at Array.indexOf
vs. the in operator
.
Because in
looks up property names, not values. Your property names are the array indices.
From MDN's page on the in
operator:
The in operator returns true if the specified property is in the specified object.
prop
A string or numeric expression representing a property name or array index
Note a property name or array index. The in
operator does not search for property values, but for property names. In this case, the property names are 0
and 1
, so 0 in markets
will return true.
You should use indexOf
, in browsers that support it, and shim it in those that don't.
Because in
is meant for objects, not arrays. If you want to reliably do this you have to search through each element in the array:
for( var i=0, l=markets.length; i<l; i++ ){
if( markets[i] === 'AB' ){
// do something
}
}
The following will work, which is what you're thinking:
var markets = { AB: 1, CD: 1 };
console.log( "AB" in markets );
In only works when you are using an object, not an array. So this will work:
var markets = {
AB: 'AB',
CD: 'CD'
};
'AB' in markets; // true
As said in
won't help you in this case.
I guess you'll have to write a searching function.
Here's one:
function inArray(ArrObj, Search){
var exists = false;
for (var i = 0; i < ArrObj.length; i++){
if (ArrObj[i] == Search){
return true;
var exists = true;
break;
}
else if ((i == (ArrObj.length - 1)) && (!exists)){
if (ArrObj[i] != Search){
return false;
}
}
}
}