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

后端 未结 5 1429
野性不改
野性不改 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:14

    The only correct way is to check the index vs. the length.

    An element may be assigned the value undefined. It is just silly to use it for a sentinel here. (There may be other, valid and possibly overlapping, reasons for checking for undefined, but not "for an out of bound check" -- the code in the other question will present arguably wrong results when the value of the given arg is really undefined.)

    Happy coding.

提交回复
热议问题