[英]Using value from input field as key in js object
I want to take input from user into input field and after extracting the value, I want to add this in a js object with key.我想将用户的输入输入到输入字段中,在提取值后,我想将其添加到带有键的 js 对象中。 My code:
我的代码:
<!DOCTYPE html> <html> <body> <input type="text" id="task"> <button onclick="add_ele()">add</button> <p id="para"></p> <script> var l={} var count=0; function add_ele(){ var x = document.getElementById("task").value; var count=count+1; var pair= {count:x}; l={...l,...pair}; document.getElementById("para").innerHTML = JSON.stringify(l); } </script> </body> </html>
Output which I am getting:我得到的输出:
The desired output is所需的输出是
l={1:"some message from input text", 2:"some message from input text", .. and so on}
But output which I am getting is {"count":"some text"}
但是我得到的输出是
{"count":"some text"}
Why this count is not replaced by count value which I am incrementing?为什么这个计数没有被我正在递增的计数值替换?
I think you want something like this.我想你想要这样的东西。 You receive an array with objects.
您会收到一个包含对象的数组。
var a = []; function add_ele() { var x = document.getElementById("task").value; //Adding object to array. The key is the array length + 1 a.push({ [a.length+1]: x }); document.getElementById("para").innerHTML = JSON.stringify(a); }
<input type="text" id="task"> <button onclick="add_ele()">add</button> <p id="para"></p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.