简体   繁体   English

使用Javascript从用户输入追加数组

[英]Appending an array from user input in Javascript

Hey guys I'm pretty new to JavaScript. 大家好,我是JavaScript新手。 Long story short is I'm starting a web dev boot camp next week so I can have a career change after the new year. 长话短说,我下周将开始一个网络开发新手训练营,这样我就可以在新年之后改变职业。 I totally get HTML and CSS, and I've done a bit of swift. 我完全掌握了HTML和CSS,并且做得很快。 Anyway Arrays are kind of “that thing” that gets to me, so I thought I would challenge myself by just giving little tasks and seeing if I could do it. 无论如何,数组是进入我的“那个东西”,所以我认为我会挑战自己,只做一些小任务,看看是否可以做到。 This one was appending an array from user input, then displaying it. 这是从用户输入追加一个数组,然后显示它。 I've been working on it for a while and searched through sample code and other forums and am at a loss. 我已经研究了一段时间,并在示例代码和其他论坛中进行了搜索,但很茫然。 Now I am using a basic text editor as I do these at work during “down time” if you catch my drift so maybe it's a typo that fresh eyes may catch. 现在,我正在使用基本的文本编辑器,因为如果您发现我的漂移,我会在“停工期”工作时进行这些工作,所以也许这是新鲜的眼睛可能会遇到的错字。

Anyway much appreciate any advice. 无论如何,我们非常感谢任何建议。

<!doctype html>
 <html>
<head>


<meta charset="utf-8" />
 <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
 <meta name="viewport" content="width=device-width, initial-scale=1" />
</head>


  <body>

  <input id="names" />
 <button id="nameSubmit">Please Enter A Name</button>
<p id="output"></p>


  <script>


  document.getElementById("nameSubmit").onclick = function(); {

 var nameArray = ["Sean", "Ryan", "Amanda"];
 var name = document.getElementById("names").value;

      nameArray.push("name");
       nameArray.ToString();
       document.getElementById("output").innerhtml = nameArray;

  }



   </script>

   </body>

      </html>

You have some basic mistakes 你有一些基本的错误

nameArray.push("name");  //You are pushing the string name, not the variable
nameArray.ToString();    //Does nothing
document.getElementById("output").innerhtml = nameArray;  //there is no innerhtml, case matters.

Should be 应该

nameArray.push(name);  
document.getElementById("output").innerHTML = nameArray.join(",");  

Now the issue will have is you declare the array inside of the click so it will always reset. 现在的问题是,您在点击内声明了数组,因此它将始终重置。 If you do not want it to reset, you would need to move it outside. 如果您不希望将其重置,则需要将其移到外部。


 var nameArray = ["Sean", "Ryan", "Amanda"]; document.getElementById("nameSubmit").onclick = function() { var name = document.getElementById("names").value; nameArray.push(name); document.getElementById("output").innerHTML = nameArray.join(","); }; 
 <input id="names" /> <button id="nameSubmit">Please Enter A Name</button> <p id="output"></p> 

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

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