Check if an array item is set in JS

前端 未结 9 1110
别跟我提以往
别跟我提以往 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:49

    This is not an Array. Better declare it like this:

    var assoc_pagine = {};
    assoc_pagine["home"]=0;
    assoc_pagine["about"]=1;
    assoc_pagine["work"]=2;
    

    or

    var assoc_pagine = {
                     home:0,
                     about:1,
                     work:2
                   };
    

    To check if an object contains some label you simply do something like this:

    if('work' in assoc_pagine){
       // do your thing
    };
    

提交回复
热议问题