Javascript foreach loop on associative array object

后端 未结 9 916
伪装坚强ぢ
伪装坚强ぢ 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:31

    The .length property only tracks properties with numeric indexes (keys). You're using strings for keys.

    You can do this:

    var arr_jq_TabContents = {}; // no need for an array
    
    arr_jq_TabContents["Main"] = jq_TabContents_Main;
    arr_jq_TabContents["Guide"] = jq_TabContents_Guide;
    arr_jq_TabContents["Articles"] = jq_TabContents_Articles;
    arr_jq_TabContents["Forum"] = jq_TabContents_Forum;
    
    for (var key in arr_jq_TabContents) {
        console.log(arr_jq_TabContents[key]);
    }
    

    To be safe, it's a good idea in loops like that to make sure that none of the properties are unexpected results of inheritance:

    for (var key in arr_jq_TabContents) {
      if (arr_jq_TabContents.hasOwnProperty(key))
        console.log(arr_jq_TabContents[key]);
    }
    

    edit — it's probably a good idea now to note that the Object.keys() function is available on modern browsers and in Node etc. That function returns the "own" keys of an object, as an array:

    Object.keys(arr_jq_TabContents).forEach(function(key, index) {
      console.log(this[key]);
    }, arr_jq_TabContents);
    

    The callback function passed to .forEach() is called with each key and the key's index in the array returned by Object.keys(). It's also passed the array through which the function is iterating, but that array is not really useful to us; we need the original object. That can be accessed directly by name, but (in my opinion) it's a little nicer to pass it explicitly, which is done by passing a second argument to .forEach() — the original object — which will be bound as this inside the callback. (Just saw that this was noted in a comment below.)

    0 讨论(0)
  • 2020-12-02 05:37

    This is very simple approach. The Advantage is you can get keys as well:

    for (var key in array) {
        var value = array[key];
        console.log(key, value);
    }
    

    For ES6:

    array.forEach(value => {
      console.log(value)
    })  
    

    For ES6: (If you want value, index and the array itself)

    array.forEach((value, index, self) => {
      console.log(value, index, self)
    })  
    
    0 讨论(0)
  • 2020-12-02 05:38

    arr_jq_TabContents[key] sees the array as an 0-index form.

    0 讨论(0)
提交回复
热议问题