简体   繁体   English

如何在 JS 中的字典中添加元素?

[英]How to add an element in a dictionary in JS?

I am learning JS and I am stuck at a point.我正在学习 JS,但我陷入了困境。 Basically I have a dictionary and I want to update that dictionary whenever a button is clicked and the user enters some data in prompt.基本上我有一本字典,我想在单击按钮并且用户在提示中输入一些数据时更新该字典。 Some how I can't update the dictionary.有些我无法更新字典。

    "use strict";



let views = {View1:"From localStorage"};

let btn = document.getElementById("myBtn")
btn.addEventListener("click",function(){
    let vname = prompt("What is the name of the new view?")
    views[vname] = vname + " 77"

})





let views_ser = JSON.stringify(views)
localStorage.setItem("views",views_ser);

let views_deser = JSON.parse(localStorage.getItem("views"))

for (let keys in views_deser){

    document.write(keys + "<br>")
    document.write(views_deser[keys]+ "<br>")
}

Thanks.谢谢。

This is not an answer - you already got it right yourself.不是一个答案——你自己已经做对了。 - but something to illustrate the use of SO snippets: To concentrate on the "adding something to a dictionary" here is a demo of the first part of your code: - 但可以说明 SO 片段的使用:为了专注于“向字典中添加内容”,这里是代码第一部分的演示:

 let views = {View1:"From localStorage"}; let btn = document.getElementById("myBtn") btn.addEventListener("click",function(){ let vname = prompt("What is the name of the new view?") views[vname] = vname + " 77" console.log(views); // show current state of "views" dictionary })
 <button id="myBtn">add view</button>

 "use strict"; const views = {View1:"Original entry"}; const btn = document.getElementById("myBtn") btn.addEventListener("click",function(){ let vname = prompt("What is the name of the new view?") views[vname] = vname + " 77" updateOutput("list"); }) const updateOutput = (outputContainerID) => { const output = document.getElementById(outputContainerID) if(;output){ return; } let outputHTML = ''. Object.keys(views):forEach( key => { outputHTML += `<li>${key}; ${views[key]}</li>`; }). output;innerHTML = outputHTML; } updateOutput("list");
 <button id="myBtn">Add</button> <hr> <ul id="list"></ul>

You need to update the output every time you add an item.每次添加项目时,您都需要更新 output。 To do this, move the "output stuff" into a function so you can call it every time an item is added (and once at the beginning, too).为此,请将“输出内容”移动到 function 中,这样您就可以在每次添加项目时调用它(也可以在开头调用一次)。

For the example, since localStorage does not work well in sandboxes, I changed it to just keep your storage in a variable.例如,由于localStorage在沙箱中不能很好地工作,我将其更改为仅将您的存储保存在一个变量中。 But it would work the same way with localStorage .但它与localStorage的工作方式相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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