JavaScript基础教程

文章39 |   阅读 20706 |   点赞0

来源:https://blog.csdn.net/u011541946/category_6887610.html

JavaScript学习笔记31-利用循环语句给数组添加元素

x33g5p2x  于2022-03-06 转载在 其他  
字(0.6k)|赞(0)|评价(0)|浏览(519)

本文来介绍如何使用循环语句给数组添加元素。有时候,我们需要用户的输入,拿到这个输入的字符,保存到数组里去,这个需要for语句和prompt()方法。

  1. <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html>
  4. <head>
  5. </head>
  6. <body>
  7. <script type ="text/javascript">
  8. var names = new Array(3);
  9. for(i=0;i<3;i++){
  10. names[i] = prompt("Enter some name here:", "");
  11. }
  12. document.write("All the element in Array are: "+names[0] + names[1]+ names[2]);
  13. </script>
  14. </body>
  15. </html>

上面例子会循环执行三次prompt()方法,刚刚是三个元素,这个和数组Arrar(3)大小相符。这里强调是数组都是索引从0开始,但是长度是最大的索引下标加1.

相关文章