Check if an array item is set in JS

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

    var assoc_pagine = new Array();
    assoc_pagine["home"]=0;
    

    Don't use an Array for this. Arrays are for numerically-indexed lists. Just use a plain Object ({}).

    What you are thinking of with the 'undefined' string is probably this:

    if (typeof assoc_pagine[key]!=='undefined')
    

    This is (more or less) the same as saying

    if (assoc_pagine[key]!==undefined)
    

    However, either way this is a bit ugly. You're dereferencing a key that may not exist (which would be an error in any more sensible language), and relying on JavaScript's weird hack of giving you the special undefined value for non-existent properties.

    This also doesn't quite tell you if the property really wasn't there, or if it was there but explicitly set to the undefined value.

    This is a more explicit, readable and IMO all-round better approach:

    if (key in assoc_pagine)
    

提交回复
热议问题