在jquery中为多维数组分配索引和值
我想在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 ie 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 ie 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]); } }); -Select- 1 2 3 4
这里我想将索引9设置为数组,但它添加了9个元素,
我需要只添加一个索引,即9,它的值是数组
实际上,它不会添加九个元素,只有一个元素。 那一个元素在索引8
(可能不是9
– 记住索引从0
开始); 索引0-7
根本没有值 。 这是因为JavaScript标准数组本质上是稀疏的 ( 根本不是真正的数组 )。 更多关于此的信息。
长度是10
但它应该是1,因为我只添加了一个索引,即9和它的数组
length
属性未定义为数组中条目数的计数。 它被定义为(至少)比最高数组索引大一个。 由于数组可能缺少条目,因此length
可以比数组中的条目数更多(但不能更少)。
现在,如果您不需要数组对象的数组,则可以使用普通对象。 唯一的区别是它没有length
属性,并且没有各种特定于数组的函数( forEach
等)。 要做到这一点,只需改变你的
var AllItem = new Array();
到
var AllItem = {};
您可以将[]
表示法与对象和数组一起使用(因为数组只是对象, []
表示法是对象事物,而不是数组事物),因此您的其他代码不会更改
但同样, 唯一的区别是length
属性和各种数组函数。
有关如何在索引8处添加条目的更多信息不会在0-7处创建条目:
当你这样做:
var a = []; a[8] = "value";
所有发生的事情是条目8
设置为值, a.length
设置为9
。 没有其他任何内容添加到数组中。
console.log(0 in a); // false console.log(1 in a); // false ... console.log(7 in a); // false console.log(8 in a); // true!
人们有时难以绕过它,但关键是它在上面的链接文章中:数组根本不是数组,它们只是带有一点魔力的对象。数组“索引”只是属性名称和数组“条目”只是属性。 因此a[8] = "value"
会在对象上创建一个名为“8” a
属性。 它不会创建任何其他属性。
当您读取不存在的属性的值(在对象或其原型上)时,您将返回undefined
的值,但这并不意味着该属性存在,这就是如何定义JavaScript以处理该情况(阅读不存在的财产)。
使用in
运算符(上面使用的)和hasOwnProperty
函数可以测试属性是否存在( in
查看ojbect及其原型时, hasOwnProperty
只查看对象)。
关于更新后的代码,请回答下面的问题,这条线可能会也可能不会成为问题,具体取决于您拥有的其他代码:
AllItem[CategoryCode][dropdownumber] = SelectedVal;
如果你已经在AllItem[CategoryCode]
放置了一个对象或数组,那AllItem[CategoryCode]
。 如果还没有,则会导致错误。
如果你知道你已经这样做了,那么就行了。
如果你知道你没有这样做,那么:
AllItem[CategoryCode] = []; AllItem[CategoryCode][dropdownumber] = SelectedVal;
如果您可能会或可能不会这样做,那么:
if (!AllItem[CategoryCode]) { AllItem[CategoryCode] = []; } AllItem[CategoryCode][dropdownumber] = SelectedVal;
(或者有时你会看到这个:
(AllItem[CategoryCode] = AllItem[CategoryCode] || [])[dropdownumber] = SelectedVal;
但通常不需要那种难以阅读且难以调试的东西。)