Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
51
rated 0 times [  54] [ 3]  / answers: 1 / hits: 15580  / 13 Years ago, fri, april 1, 2011, 12:00:00

I just want to ask if the in_array_orig and in_array_new is just the same.
and also im confused on the result when comparing both array (aArr1 vs aArr2).



can someone explain me. thanks



Here is my sample test code



function echo(s)
{
document.write(s);
}

function in_array_orig(oItem, aArray)
{
for (var i=0; i<aArray.length; i++) if (aArray[i] == oItem) return true;

return false;
}

function in_array_new(oItem, aArray)
{
for (var i in aArray) if (aArray[i] == oItem) return true;

return false;
}

var a = ['gab', '24', 'manila'];

var aArr1 = [1];
var b = {0:aArr1, 1:24, 2:'manila'};

var aArr2 = [1];


echo(in_array_orig(24, a)); // true
echo(in_array_new(24, b)); // true

echo(in_array_orig(aArr2, b)); // false
echo(in_array_new(aArr2, b)); // false

echo ((aArr1==aArr2)); // false
echo ((aArr1===aArr2)); // false


thanks in advance


More From » for-loop

 Answers
123

The in operator returns true if the property is in the object. This includes a lookup right up through the prototype chain. For example:



Object.prototype.k = 5;
f = {};
'k' in f; // true


Even though f is an empty object, it's prototype (as all types in JS) includes that of Object, which has the property 'k'.



Although you didn't ask, a useful function here to check the object's own properties only, is .hasOwnProperty(), so in our example above:



f.hasOwnProperty('k'); // false, that's more what we would expect


Although for arrays you don't (usually) want to iterate over all properties, since these properties may include things other than index values, so both for reasons of performance and expected behaviour, a regular for(var i=0;i<n;i++) should be used.



As such, if you're using arrays go with in_array_orig, and for objects where you are interested in their properties, use in_array_new (which should be renamed appropriately, in_obj or something).



In addition, [1] == [1] returns false since the two objects/arrays are not the same object. Indeed each of their properties and indexes have the same value, although they aren't sitting at the same place in memory, and thus are not considered equal. You can easily build (or find on the net) a deep search equals() routine to check whether two objects/arrays are indeed equal in value (as opposed to address).


[#92969] Thursday, March 31, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anais

Total Points: 672
Total Questions: 118
Total Answers: 121

Location: Oman
Member since Fri, Dec 23, 2022
1 Year ago
;