[英]add values to multidemensional array
我有此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]未定義
我的錯在哪里
Javascript是異步的...您不能期望兩個函數可以依次執行... :-)
這種方法可以工作...但是您必須以這種方式初始化初始數組:
var items = [ [], [] ];
由於與
var items = [[]];
您只需要在外部數組( items[0]
)中定義一個內部數組,但是要兩個( items[0]
, items[1]
)。
var items = [[]];
您的問題在這里。
items [0]是一個數組。 但是items [1]未定義。 為了工作,您需要將項目定義為[[],[]]
為了使它更具動態性,您可以在$ .each之前檢查是否存在items [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());
});
然后它應該可以正常工作。
我認為您對“推送”功能感到困惑。 該函數在數組的最后位置插入一個新元素。
例如
var items = ["grape"];
items.push("apple");
console.log(items); //["grape", "apple"].
最好的方法是創建一個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;
將靜態多維數組與通過push動態添加元素結合使用時要小心。
嘗試下面的代碼,這對於兩個維度是動態的。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.