JavaScript在循环访问.innerhtml中的数组和输出时使用 [英] Javascript While Looping Through Array And Outputting in .innerhtml
问题描述
我是Javascript的全新人物,自学自学。我试图设置一个函数,它将写入数组元素之间的空格 AmericanCars
的每个元素。
I'm brand new to Javascript and teaching myself. I'm trying to setup a function that will write each of the elements of the array AmericanCars
with a space between the elements.
我有这个工作,所以当我使用 .innerHTML = AmericanCars [Index Position]
加上一个不破空间,我可以写入数组的一个元素。现在我试图用来循环它,而
循环,但我只是得到了未定义的输出。
I have it working so that when I use .innerHTML=AmericanCars[Index Position]
plus a non-breaking space, I can write one element of the array. Now I'm trying to loop through it with a while
loop, but I just get an output of "undefined."
我如何获得 .innerHTML
来写出数组中每个元素之间的空格?是否有一种方法比使用While循环更简单,或者是我的While循环格式错误。
How can I get .innerHTML
to write out each of the elements of an array with a space between them? Is there a method that is simpler than using the While loop or is my While loop just formatted wrong.
<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
var AmericanCars=["Chevy", "Ford", "Dodge"];
var JapaneseCars=["Honda", "Toyota", "Subaru"];
var FavoriteCars=[];
function ListAmericanCars() {
var arraycounter = 0;
/* Use array counter to set the value that is displayed in innerHTML's square [] brackets */
while (arraycounter <= AmericanCars.length) {
document.getElementById('content').innerHTML = AmericanCars[arraycounter] + "  ";
arraycounter++;
}
}
</script>
<p> What Are Your Favorite American Cars? Answer:
<span id="content">______________
</span>
</p>
<button onclick="ListAmericanCars()">
American Cars Function
</button>
</body>
</html>
推荐答案
数组是基于0的。
while (arraycounter < AmericanCars.length) {
...
}
另外,您可以这样做:
document.getElementById('content').innerHTML = AmericanCars.join(' ');
这篇关于JavaScript在循环访问.innerhtml中的数组和输出时使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!