JavaScript在循环访问.innerhtml中的数组和输出时使用 [英] Javascript While Looping Through Array And Outputting in .innerhtml

查看:148
本文介绍了JavaScript在循环访问.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] + "&nbsp ";
                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('&nbsp');

这篇关于JavaScript在循环访问.innerhtml中的数组和输出时使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆