how to fetch array keys with jQuery?

前端 未结 6 970
北海茫月
北海茫月 2020-12-03 04:19

Good afternoon. I have an array with some keys, and values in them. I then need to fetch the array keys and not the data in them. I want to do this with jQuery. I know for e

6条回答
  •  借酒劲吻你
    2020-12-03 05:01

    Use an object (key/value pairs, the nearest JavaScript has to an associative array) for this and not the array object. Other than that, I believe that is the most elegant way

    var foo = {};
    foo['alfa'] = "first item";
    foo['beta'] = "second item";
    
    for (var key in foo) {
            console.log(key);
    }
    

    Note: JavaScript doesn't guarantee any particular order for the properties. So you cannot expect the property that was defined first to appear first, it might come last.

    EDIT:

    In response to your comment, I believe that this article best sums up the cases for why arrays in JavaScript should not be used in this fashion -

    • "Associative Arrays" considered Harmful

提交回复
热议问题