Array Out of Bounds: Comparison with undefined, or length check?

后端 未结 5 1453
野性不改
野性不改 2020-12-29 04:35

this seems to be a common javascript idiom:

function foo (array, index) {
    if (typeof array[index] == \'undefined\')
        alert (\'out of bounds baby\'         


        
5条回答
  •  攒了一身酷
    2020-12-29 05:09

    It's not common as far as I know, much more common is:

    for (var i=0, iLen=array.length; i

    You should not compare to undefined, since a member of the array may have been assigned a value of undefined, or may not have been assigned any value.

    e.g.

    var a = [0,,,,];
    
    alert(a.length); // 4 (or 5 in buggy IE);
    
    a[1] === undefined; // true but not out of bounds
    

    The main reason for using a for loop is that array properties may not be returned in numeric order if a for..in loop is used.

    A for..in loop is much more efficient in sparse arrays but the possible out-of-order access must be dealt with if it matters (as must inherited and non-numeric enumerable properties if they should be avoided).

提交回复
热议问题