JavaScript基础教程

文章39 |   阅读 11541 |   点赞0

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

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

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

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

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html>  
<head>  
</head>  
<body>  

<script type ="text/javascript">  

var names = new Array(3);
for(i=0;i<3;i++){
	
	names[i] = prompt("Enter some name here:", "");
}

document.write("All the element in Array are:  "+names[0] + names[1]+ names[2]);

</script>  

</body>  
</html>

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

相关文章