如何使用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);
});
答案 0 :(得分:0)
旧答案:您的脚本可能无效,因为您必须初始化循环索引: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);
});