具有重复名称的JS关联数组 [英] JS associative array with duplicate names

查看:153
本文介绍了具有重复名称的JS关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,所以我有一个数组:

  var myarray = {
field_1:lorem ipsum,
field_2:1,
field_2:2,
field_2:6
};

如您所见,数组中有重复的名称,但具有不同的值。如果我通过它(使用jQuery):

  $。each(myarray,function(key,value)
{
console.log(key);
console.log(myarray [key]);
console.log(myarray [value]);
}

键 - 返回正确的键
myarray [key] - 返回该键的名称
myarray [value] - 返回最后一个元素,该名称的值为

对于field_2来说,它将返回6,尽管它会打印3次,因为它在数组中重复3次。



我的问题是如何获得该重复命名字段的正确值,而不仅仅是最后一个的



谢谢

解决方案

这不是一个对象的数组,你最好创建一个对象的属性一个数组,并存储不同的值。

  var myarray = {
field_1:lorem ipsum ,
field_array:[]
};

myarray.field_array.push(值);

然后只需循环该数组的该属性。


ok, so I have an array like:

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

as you see there are duplicate names in the array, but with different values. If i go through it like (using jQuery):

$.each(myarray, function(key, value)
{
   console.log(key);
   console.log(myarray[key]);
   console.log(myarray[value]);
}

key - returns the correct key
myarray[key] - returns the name for that key
myarray[value] - returns the last elements', with that name, value

meaning for field_2 it will return 6, though it'll print it 3 times, as it repeats 3 times in the array.

My question is how to obtain the correct value for that duplicate named fields and not just the last one's

Thank you

解决方案

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.

这篇关于具有重复名称的JS关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆