删除关联数组中的元素

时间:2018-01-03 23:35:39

标签: javascript arrays

如何创建一组按钮,单击这些按钮会删除存储在关联数组中的各个元素?我已经尝试了拼接元素..但它似乎没有用。我是编程新手,所以任何帮助都会受到赞赏。感谢

bodyText = bodyText + '<input type="button" id="btnDeleteQuestion" 
value="Delete a question" onClick="questionBank.splice.(0,1) ">';

1 个答案:

答案 0 :(得分:2)

JavaScript中的关联数组是具有键/值对的普通旧对象。使用delete运算符删除密钥。

&#13;
&#13;
var myObject = {
  key1:"key1Value",
  key2:"key2Value",
  key3:"key3Value",  
  key4:"key4Value"  
};

console.log(myObject);

document.getElementById("btnDeleteQuestion").addEventListener("click", function(){
  delete myObject["key4"];
  console.log(myObject);  
});
&#13;
<input type="button" id="btnDeleteQuestion" value="Delete a question">
&#13;
&#13;
&#13;