向多维数组添加值

时间:2019-01-30 13:01:47

标签: javascript arrays

我有这个javascript代码,可以生成具有静态值的多数组:

var items = [ ["red", "blue"], ["green", "yellow"] ];
console.log(items[1][1]); // green

但是现在我想动态填充值。 我尝试过:

var items = [[]];
$.each($("input[name='checkboxColors1']:checked"), function(){            
   items[0].push($(this).val());
});

$.each($("input[name='checkboxColors2']:checked"), function(){            
    items[1].push($(this).val());
});

items [0] .push ...有效,但items [1]无效

  

TypeError:items [1]未定义

我的错在哪里?

6 个答案:

答案 0 :(得分:2)

JavaScript是异步的...您不能期望两个函数可以依次执行...:-)

这种方式可以工作...但是您必须以这种方式初始化初始数组:

var items = [ [], [] ];

var items = [[]];

您只能在外部数组(items[0])中定义一个内部数组,但是您想要两个(items[0]items[1])。

答案 1 :(得分:2)

var items = [[]];,您的问题在这里。

items [0]是一个数组。但是items [1]未定义。 为了工作,您需要将项目定义为[[],[]]

或者为了使其更具动态性,您可以在$ .each之前检查是否存在items [1],如果没有创建

答案 2 :(得分:1)

您不能将其放入未定义的数组中,首先需要创建该数组。

您的代码必须看起来像这样:

var items = [[], []];
$.each($("input[name='checkboxColors1']:checked"), function(){            
   items[0].push($(this).val());
});

$.each($("input[name='checkboxColors2']:checked"), function(){            
    items[1].push($(this).val());
});

然后它应该可以正常工作。

答案 3 :(得分:0)

我认为您对“推送”功能感到困惑。 该函数在数组的最后一个位置插入一个新元素。

例如

ffmpeg

答案 4 :(得分:0)

最好的方法是创建一个Array对象并动态分配值。这样,您还可以定义字符串键。请参见下文

var items = new Array();

    items[0] = 1;
    items[1] = 2;
    console.log(items);

//Uncomment above block to test.
var items = new Array();
var items0 = [];
var items1 = [];
$.each($("input[name='checkboxColors1']:checked"), function(){            
   items0 = $(this).val();
});

$.each($("input[name='checkboxColors2']:checked"), function(){            
    items1 = $(this).val();
});
items[0] = items0;
items[1] = items1;

答案 5 :(得分:0)

在结合使用静态多维数组和通过推动态添加元素时要小心。

尝试下面的代码,该代码对于两个维度都是动态的。

var checkBoxGroupNames = ['checkboxColors1', 'checkboxColors2'];
var items = [];

var checkedChkBoxes = [];

for (var i = 0; i < checkBoxGroupNames.length; i++) {
    checkedChkBoxes = [];

    $.each($("input[name=" + checkBoxGroupNames[i] + "]:checked"), function(){
        checkedChkBoxes.push($(this).val());
    });

    items.push(checkedChkBoxes);
}

console.log(items); // items now holds the two dimension array

对于更简洁的代码,您可以将查找每个组中选中的复选框的逻辑放入函数中。

var checkBoxGroupNames = ['checkboxColors1', 'checkboxColors2'];
var items = [];

$.each(checkBoxGroupNames, function(){
  items.push(GetCheckedChkBoxes(this));
});

console.log(items); // items now holds the two dimension array

function GetCheckedChkBoxes(chkBoxGroupName) {
  checkedChkBoxes = [];

  $.each($("input[name=" + chkBoxGroupName + "]:checked"), function(){
    checkedChkBoxes.push($(this).val());
  });

  return checkedChkBoxes;
}
相关问题