[英]Dynamically push new column in 2D array
我正在嘗試使用jQuery通過以下代碼在2D數組中動態添加新值:
var disabledTime = [[]];
var index = 0;
$("#addTimeSlot").click(function(){
// do some stuff here...
disabledTime[index].push($('.slotTime').last().prev().val());
disabledTime[index].push($('.slotTime').last().val());
}
當index
為0
一切正常,但是遞增后會給我一個錯誤:“未定義不是對象”。
我需要創建類似[['1','2'],['3','4']]
,其中元素是動態添加的。 誰能幫我? 謝謝。
那是因為當index
不為零時,數組中的元素是undefined
。 將元素初始化為空數組將起作用。
var disabledTime = [[]];
var index = 0;
$("#addTimeSlot").click(function () {
//do some stuff here...
// Check if the element at `index` is not undefined.
if (disabledTime[index] === undefined) {
// Initialize to empty array.
disabledTime[index] = [];
}
disabledTime[index].push($('.slotTime').last().prev().val());
disabledTime[index].push($('.slotTime').last().val());
});
這是因為只有索引0具有數組。
您不能推送到不是數組本身的索引。
只是從一個空數組開始,然后先將數組推入該數組:
var disabledTime=[];
var index = 0;
$("#addTimeSlot").click(function(){
//do some stuff here...
disabledTime.push([]);
disabledTime[index].push($('.slotTime').last().prev().val());
disabledTime[index].push($('.slotTime').last().val());
您的數組為[[]]
表示它包含一個在0處為空的數組,在所有其他索引處均未定義
基本上可以做到: array[index] = []
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.