[英]How to use array.push on array with a defined index?
如何使用array.push在數組中添加帶有自定義索引的對象?
我有這個腳本,但它不起作用。 Chrome的Javascript控制台未輸出錯誤
var tempList = new Array();
$('#add').click(function(){
var split = $('#itemid').val().split('_');
var itemid = split['0'];
var lbs = $('#lbs').val();
tempList.push(tempList['itemid'] = lbs);
for (var i; i<=(tempList.length - 1); i++){
if (i==0){
var list = tempList[i]+ '<br />';
}
else{
var list = list + tempList[i]+ '<br />';
}
}
alert(list);
});
舊答案:您的腳本可能無法運行,因為您必須初始化循環索引: var i=0;
嗨,希望您別介意另一個問題,但是如何在表中顯示
tempList[]
的內容?
答 :
請參見下面的代碼。 循環之后,我提供了幾種將數據/表追加到主體的方法,因為您沒有指定所需的方法。
var tempList = {}; $('#add').click(function(){ var split = $('#itemid').val().split('_'); var returnTable = "<thead><tr><th>ItemId</th><th>Lbs</th></tr></thead><tbody>"; var itemid = split[0]; if(/^\\d+$/.test(itemid)) return; //itemId is not a valid number: return now. var lbs = $('#lbs').val(); tempList[itemid] = lbs; //refer by value, removed quotes around `itemId`. for (var i in tempList){ returnTable += "<tr><td>" + i + "</td><td>" + tempList[i] + '</td></tr>'; } returnTable += "</tbody>"; var tbl = document.createElement("table"); tbl.innerHTML = returnTable; //Various methods to add the table to your document are shown below // For each example, I assume that that specific element exists //When the data should be APPENDED to an existing TABLE ("#existingTable") var tblTo = document.getElementById("existingTable").tBodies[0]; for(var i=0, len=tbl.tBodies[0].rows.length; i<len; i++){ tblTo.appendChild(tbl.tBodies[0].rows[0]); //Removes the row from the temporary table, appends row to tblTo } //When the new table should replace the previous table ("#prevTable"): var prevTbl = document.getElementById("prevTable"); prevTbl.parentNode.replaceChild(tbl, prevTbl); //When the table should be APPENDED to a container ("#container") document.getElementById("output").appendChild(tbl); //When the new table should replace the contents of a container ("#container") var container = document.getElementById("container"); container.innerHTML = ""; container.appendChild(tbl); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.