【发布时间】:2014-08-03 09:30:03
【问题描述】:
我想在 jquery 中向多维数组添加特定(数字)索引,然后在这些索引处分配值。每个索引本身都是一个数组,这些子数组的索引也将被动态分配。
$(document).ready(function(){
$('#Show').click(function(){
var AllItem = new Array();
$("select[name^='Item']").each(function(dropdownumber, selected) {
var name = $(this).attr('name');
var toRemove = 'Item[';
var name1 = name.replace(toRemove,'');
var CategoryCode = name1.replace(']','');
alert('item category code = ' + CategoryCode);
if (!AllItem[CategoryCode]){
//here I want that index 9 is set as an array, but it adds 9 elements ,
//I need that only one index is added i.e. 9 and its value is array
AllItem[CategoryCode] = [];
alert('added='+CategoryCode);
}
//length comes out to be 10
//but it should be 1 as I have added only one index i.e. 9 & its an array
alert('length='+AllItem.length);
//after this I need to assign values at 9th index of the array like
// AllItem[9][0] = 2; //the value of the first index of 9th index is 2
// AllItem[9][1] = 5;
// AllItem[9][2] = 6;
// AllItem[9][3] = 9;
更新:
//for adding values at indexes of AllItem : AllItem[9][1] = 5;
$(this).find(':selected').each(function(selectedoptionnumber, selected) {
var SelectedVal = $(selected).val();
if (SelectedVal > 0) {
AllItem[CategoryCode][dropdownumber] = SelectedVal;
alert(' Code = ' + AllItem[CategoryCode][dropdownumber]);
}
});
<table style="border: 2px solid #97BDC9; border-collapse:collapse;">
<tbody>
<tr>
<td>
<select name="Item[9]">
<option selected="selected" value="0">-Select-</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="button" id="Show" value="Show Selected Items" />
</td>
</tr>
</tbody>
</table>
【问题讨论】:
-
最好在这里使用
objects。 -
@Mritunjay:如何使用对象?能否请您提及代码
-
@sqlchild:我在我的回答中涵盖了它。
标签: javascript jquery arrays multidimensional-array