簡體   English   中英

我如何使用document.getElementById獲得二維數組

[英]How can I get a 2d array using document.getElementById

我正在嘗試使用document.getElementById(“ clients”)。value.split(',');獲得2D數組。 因為我需要拆分2d數組。

我已經嘗試了上面的代碼/步驟。

<input type="hidden" id="clients" name="clients"  value="{{clients}}">

var displayClient = [];
var clients_array = document.getElementByName("clients").value.split(',');

var itemDisp = [];
var arrayLength = clients_array.length;
for (var i = 0; i < arrayLength; i++) {
    displayClient.push(clients_array[i] + ' - ' + clients_array[i]);
    itemDisp.push({ label: displayClient[i]});
}

//the 2d array is as follows
[['1', 'client 1'], ['2', 'client 2']]

目前的實際結果是:[['1'(新行)'客戶端1'] ...而我想得到:1-客戶端1 ...

例如,參見函數inputHandler
有關將HTMLCollection轉換為數組的更多信息,請參見將HTMLCollection轉換為數組的最有效方法。

 // create elements fetch('http://jsonplaceholder.typicode.com/users') .then(res=>res.json()) .then(users => { users.forEach(function(user) { var input = document.createElement('input'); input.value = user.name; input.name = 'clients'; document.body.appendChild(input); inputHandler(); }); }) .catch(err => { throw err; }); function inputHandler() { var inputs = document.getElementsByName('clients'); inputsArr = Array.prototype.slice.call(inputs); inputsArr.forEach(function(element) { console.log(element.value); }); // or use that HTMLCollection iterable console.log('👍 HTMLCollection iterable'); for (var counter = 0; counter < inputs.length; counter++) { console.log(inputs[counter].value); // or other operations } } 

暫無
暫無

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

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