Javascript foreach loop on associative array object

后端 未结 9 971
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 04:41

Why my for for-each loop is not iterating over my JavaScript associative array object?

// defining an array
var array = [];

// assigning values to correspon         


        
9条回答
  •  青春惊慌失措
    2020-12-02 05:24

    This is (essentially) incorrect in most cases:

    var array = [];
    array["Main"] = "Main page";
    

    That creates a non-element property on the array with the name Main. Although arrays are objects, normally you don't want to create non-element properties on them.

    If you want to index into array by those names, typically you'd use a Map or a plain object, not an array.

    With a Map (ES2015+), which I'll call map because I'm creative:

    let map = new Map();
    map.set("Main", "Main page");
    

    you then iterate it using the iterators from its values, keys, or entries methods, for instance:

    for (const value of map.values()) {
        // Here, `value` will be `"Main page"`, etc.
    }
    

    Using a plain object, which I'll creatively call obj:

    let obj = Object.create(null); // Creates an object with no prototype
    obj.Main = "Main page"; // Or: `obj["Main"] = "Main page";`
    

    you'd then iterate its contents using Object.keys, Object.values, or Object.entries, for instance:

    for (const value of Object.values(proches_X)) {
        // Here, `value` will be `"Main page"`, etc.
    }
    

提交回复
热议问题