在jquery中创建一个关联数组

这是我到目前为止, 鞋类型boots, wellingtons, leather, trainers (in that order)

我想迭代并分配值,所以我有类似的东西

 var shoeArray = { boots : '3', wellingtons: '0', leather : '1', trainers: '3'}; 

目前我只得到一个{3,0,1,3}的数组,我可以使用它,但它不是很有帮助。

 function shoe_types() { var shoeArray = []; $('[type=number]').each(function(){ $('span[data-field='+$(this).attr('id')+']').text($(this).val()); shoeArray.push ( parseInt($(this).val()) ); }); return shoeArray; } 

检查此function

 function shoe_types() { var shoeArray = {}; // note this $('[type=number]').each(function(){ $('span[data-field='+$(this).attr('id')+']').text($(this).val()); shoeArray[$(this).attr('id')] = parseInt($(this).val()) ; }); return shoeArray; } 

PS:假设$(this).attr('id')拥有所有鞋类型

javascript中的关联数组与object相同

例:

 var a = {}; a["name"] = 12; a["description"] = "description parameter"; console.log(a); // Object {name: 12, description: "description parameter"} var b = []; b["name"] = 12; b["description"] = "description parameter"; console.log(b); // [name: 12, description: "description parameter"] 

你想要的是一个将返回一个对象的函数{}

现场演示

 function shoe_types(){ var shoeObj = {}; $('[name="number"]').each(function(){ shoeObj[this.id] = this.value; }); return shoeObj; } shoe_types(); // [object Object] 

您可以尝试在jquery中创建关联数组

 var arr = {}; $('[type=number]').each(function(){ arr.push({ $(this).attr('id'): $(this).val() }); }); console.log(arr); 

这将允许您通过ajax发送您想要通过数组传递的所有数据。

如果$(this).attr('id')是你可以尝试的那种鞋子

 shoeArray[$(this).attr('id')] = parseInt($(this).val());