for(var i in aArray) VS for(i=0; i<aArray.length; i++)

前端 未结 6 877
挽巷
挽巷 2021-01-07 10:20

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 (<

6条回答
  •  不思量自难忘°
    2021-01-07 10:47

    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 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).

提交回复
热议问题