Check if an array item is set in JS

前端 未结 9 1096
别跟我提以往
别跟我提以往 2021-02-02 08:10

I\'ve got an array

    var assoc_pagine = new Array();
    assoc_pagine[\"home\"]=0;
    assoc_pagine[\"about\"]=1;
    assoc_pagine[\"work\"]=2;
9条回答
  •  既然无缘
    2021-02-02 08:42

    TLDR; The best I can come up with is this: (Depending on your use case, there are a number of ways to optimize this function.)

    function arrayIndexExists(array, index){
        if ( typeof index !== 'number' && index === parseInt(index).toString()) {
            index = parseInt(index);
        } else {
            return false;//to avoid checking typeof again
        }
        return typeof index === 'number' && index % 1===0 && index >= 0 && array.hasOwnKey(index);
    }
    

    The other answer's examples get close and will work for some (probably most) purposes, but are technically quite incorrect for reasons I explain below.

    Javascript arrays only use 'numerical' keys. When you set an "associative key" on an array, you are actually setting a property on that array object, not an element of that array. For example, this means that the "associative key" will not be iterated over when using Array.forEach() and will not be included when calculating Array.length. (The exception for this is strings like '0' will resolve to an element of the array, but strings like ' 0' won't.)

    Additionally, checking array element or object property that doesn't exist does evaluate as undefined, but that doesn't actually tell you that the array element or object property hasn't been set yet. For example, undefined is also the result you get by calling a function that doesn't terminate with a return statement. This could lead to some strange errors and difficulty debugging code.

    This can be confusing, but can be explored very easily using your browser's javascript console. (I used chrome, each comment indicates the evaluated value of the line before it.);

    var foo = new Array();
    foo;
    //[]
    foo.length;
    //0
    foo['bar'] = 'bar';
    //"bar"
    foo;
    //[]
    foo.length;
    //0
    foo.bar;
    //"bar"
    

    This shows that associative keys are not used to access elements in the array, but for properties of the object.

    foo[0] = 0;
    //0
    foo;
    //[0]
    foo.length;
    //1
    foo[2] = undefined
    //undefined
    typeof foo[2]
    //"undefined"
    foo.length
    //3
    

    This shows that checking typeof doesn't allow you to see if an element has been set.

    var foo = new Array();
    //undefined
    foo;
    //[]
    foo[0] = 0;
    //0
    foo['0']
    //0
    foo[' 0']
    //undefined
    

    This shows the exception I mentioned above and why you can't just use parseInt();

    If you want to use associative arrays, you are better off using simple objects as other answers have recommended.

提交回复
热议问题