Literally:
(using Firefox v3.6, with for-in
caveats as previously noted
(HOWEVER the use below might endorse for-in
for this very purpose! That is, enumerating array elements that ACTUALLY exist via a property index (HOWEVER, in particular, the array length
property is NOT enumerated in the for-in
property list!).).)
(Drag & drop the following complete URI's for immediate mode browser testing.)
javascript:
function ObjInRA(ra){var has=false; for(i in ra){has=true; break;} return has;}
function check(ra){
return ['There is ',ObjInRA(ra)?'an':'NO',' object in [',ra,'].'].join('')
}
alert([
check([{}]), check([]), check([,2,3]),
check(['']), '\t (a null string)', check([,,,])
].join('\n'));
which displays:
There is an object in [[object Object]].
There is NO object in [].
There is an object in [,2,3].
There is an object in [].
(a null string)
There is NO object in [,,].
Wrinkles: if looking for a "specific" object consider:
javascript: alert({}!={}); alert({}!=={});
and thus:
javascript:
obj={prop:"value"}; ra1=[obj]; ra2=[{prop:"value"}];
alert(ra1[0]==obj); alert(ra2[0]==obj);
Often ra2
is considered to "contain" obj
as the literal entity {prop:"value"}
.
A very coarse, rudimentary, naive (as in code needs qualification enhancing) solution:
javascript:
obj={prop:"value"}; ra2=[{prop:"value"}];
alert(
ra2 . toSource() . indexOf( obj.toSource().match(/^.(.*).$/)[1] ) != -1 ?
'found' :
'missing' );
See ref: Searching for objects in JavaScript arrays.
~[1,2,3].indexOf(4)
will return 0 which will evaluate as false, whereas~[1,2,3].indexOf(3)
will return -3 which will evaluate as true. – lordvlad Oct 2 '13 at 7:59~
is not what you want to use to convert to a boolean, for that you need!
. But in this case you want to check equality with -1, s o the function might endreturn [1,2,3].indexOf(3) === -1;
~
is a binary not, it will invert each bit of the value individually. – mcfedr Jun 20 '14 at 12:49indexOf()
as per w3schools.com/jsref/jsref_indexof_array.asp. If older browser better approach is to defineprototype
forindexOf()
function as given in Array.indexOf in Internet Explorer – Lijo Jan 21 '15 at 21:42[1,2,3].indexOf(4)
will actually return -1. As @mcfedr pointed out,~
is the bitwise-NOT operator, see ES5 11.4.8. Thing is, since the binary representation of-1
consists of only 1's, it's complement is0
, which evaluates as false. The complement of any other number will be non-zero, hence true. So,~
works just fine and is often used in conjunction withindexOf
. – mknecht Mar 14 '15 at 5:35