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

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

    Do not test for undefined. You should use the length of the array. There are cases where it simply does not work to test for undefined because undefined is a legal value for legitimate array entry. Here's a legal JS array:

    var legalArray = [4, undefined, "foo"];
    

    And you can access it like this:

    var legalArray = [4, undefined, "foo"];
    
    var result = "";
    for (var i = 0; i < legalArray.length; i++) {
        result += legalArray[i] + "
    "; } $("#result").html(result);

    Generates this output:

    4
    undefined
    foo
    

    As seen in this jsFiddle: http://jsfiddle.net/jfriend00/J5PPe/

提交回复
热议问题