繁体   English   中英

如何在具有已定义索引的数组上使用array.push?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM