Javascript foreach loop on associative array object

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

    Here is a simple way to use an associative array as a generic Object type:

    Object.prototype.forEach = function(cb){
       if(this instanceof Array) return this.forEach(cb);
       let self = this;
       Object.getOwnPropertyNames(this).forEach(
          (k)=>{ cb.call(self, self[k], k); }
       );
    };
    
    Object({a:1,b:2,c:3}).forEach((value, key)=>{ 
        console.log(`key/value pair: ${key}/${value}`);
    });

    0 讨论(0)
  • 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.
    }
    
    0 讨论(0)
  • 2020-12-02 05:24

    var obj = {
      no: ["no", 32],
      nt: ["no", 32],
      nf: ["no", 32, 90]
    };
    
    count = -1; // which must be static value
    for (i in obj) {
      count++;
      if (obj.hasOwnProperty(i)) {
        console.log(obj[i][count])
      };
    };

    in this code i used brackets method for call values in array because it contained array , however briefly the idea which a variable i has a key of property and with a loop called both values of associate array

    perfect Method , if you interested, press like

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

    You can Do this

    var array = [];
    
    // assigning values to corresponding keys
    array[0] = "Main page";
    array[1] = "Guide page";
    array[2] = "Articles page";
    array[3] = "Forum board";
    
    
    array.forEach(value => {
        console.log(value)
    })
    
    0 讨论(0)
  • 2020-12-02 05:26

    If the node.js or browser supported Object.entries(), it can be used as an alternative to using Object.keys() (https://stackoverflow.com/a/18804596/225291).

    const h = {
      a: 1,
      b: 2
    };
    
    Object.entries(h).forEach(([key, value]) => console.log(value));
    // logs 1, 2

    in this example, forEach uses Destructuring assignment of an array.

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

    There are some straightforward examples already, but I notice from how you've worded your question that you probably come from a PHP background, and you're expecting JavaScript to work the same way -- it does not. A PHP array is very different from a JavaScript Array.

    In PHP, an associative array can do most of what a numerically-indexed array can (the array_* functions work, you can count() it, etc.) You simply create an array and start assigning to string-indexes instead of numeric.

    In JavaScript, everything is an object (except for primitives: string, numeric, boolean), and arrays are a certain implementation that lets you have numeric indexes. Anything pushed to an array will effect its length, and can be iterated over using Array methods (map, forEach, reduce, filter, find, etc.) However, because everything is an object, you're always free to simply assign properties, because that's something you do to any object. Square-bracket notation is simply another way to access a property, so in your case:

    array['Main'] = 'Main Page';
    

    is actually equivalent to:

    array.Main = 'Main Page';
    

    From your description, my guess is that you want an 'associative array', but for JavaScript, this is a simple case of using an object as a hashmap. Also, I know it's an example, but avoid non-meaningful names that only describe the variable type (e.g. array), and name based on what it should contain (e.g. pages). Simple objects don't have many good direct ways to iterate, so often we'll turn then into arrays first using Object methods (Object.keys in this case -- there's also entries and values being added to some browsers right now) which we can loop.

    // assigning values to corresponding keys
    const pages = {
      Main: 'Main page',
      Guide: 'Guide page',
      Articles: 'Articles page',
      Forum: 'Forum board',
    };
    
    Object.keys(pages).forEach((page) => console.log(page));
    
    0 讨论(0)
提交回复
热议问题