簡體   English   中英

創建具有動態鍵值對的數組

[英]Create array with dynamic key-value pairs

我有一張表格,其中有動態行,所以我不知道有多少行。 行中的td內,單擊按鈕時需要在數組中注冊一些內容。

我需要創建一個包含該內容的數組,但是應該采用以下格式:

array1 = [ row1:"", row2:"abc", row3:'', row4:'', row5:'xyz' ]

在這里,row1 ... row5根據行數動態變化。 默認情況下,行的值可以是“”,這很好。

提前致謝。

array1 = [ row1:"", row2:"abc", row3:'', row4:'', row5:'xyz' ]

上面的語法不正確,因此無法使用。 您可以做的是創建一個對象數組,然后使用它。

array1 = [{row1:""},{row2:"abc"}];

或者,如果行號AND值很重要,則這可能是一個更好的結構:

array1 = [{rowId:1, value:""}, {rowId:2, value:"abc"}];

編輯:

要從現有的HTML表創建這種結構,您可以查詢行並在每一行上進行操作以創建數組。

// Get a reference to the table element
var table = document.getElementById("table1");
// Initialise empty array
var array = [];

// Query for all the tr elements of the table (rows)
table.querySelectorAll('tr').forEach(function(row, index){
    // For each row, extract value from the requried column
    var value = row.children[0].innerText; // Assuming the value to be added is in the first column (td)
    // Insert new object into array for this row
    array.push({rowId:index, value: value});
})

console.log(array); // array will be an array of our objects

在@Chirag Ravindra代碼中進行了一些修改

  // Get a reference to the table element
var table = document.getElementById("table1");
// Initialise empty array
var array = [];

// Query for all the tr elements of the table (rows)
    table.querySelectorAll('tr').forEach(function(row, index){
// For each row, extract value from the requried column
var value = row.children[0].innerText; // Assuming the value to be added is in the first column (td)
// Insert new object into array for this row
array["row" + index] = value;
})

console.log(array); // array will be an array of our objects

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM