JS associative object with duplicate names

前端 未结 8 1995
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 22:51

ok, so I have an object like:

var myobject = {
   \"field_1\": \"lorem ipsum\",
   \"field_2\": 1,
   \"field_2\": 2,
   \"field_2\": 6
};

相关标签:
8条回答
  • 2020-12-10 23:54

    That is not an array that is an object. You'd be better creating a property of the object that is an array and store the different values in there.

    var myarray = {
       "field_1": "lorem ipsum",
       "field_array": []
    };
    
    myarray.field_array.push(value);
    

    then just loop through that property of the array.

    0 讨论(0)
  • 2020-12-10 23:54
    1. Your code has invalid syntax.
    2. There are no assocative arrays in Javascript
    3. The thing you defined is an Object
    4. If you give value to a property 3 times, sure it will contain the last value

    Test

    var obj = {
       "field_1": "lorem ipsum",
       "field_2": 1,
       "field_2": 2,
       "field_2": 6
    };
    
    for ( var i in obj ) {
      console.log(i + " = " + obj[i]);
    }
    

    OUTPUT

    field_1 = lorem ipsum
    field_2 = 6
    
    0 讨论(0)
提交回复
热议问题