打印在单独一行JavaScript数组的每个值 [英] Printing each value of an array on a separate line Javascript

查看:100
本文介绍了打印在单独一行JavaScript数组的每个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有涉及的Javascript以允许与网页交互的程序。这是一个棒球网站,所以我在做什么,这促使用户输入一个月。用户可以输入一个号码,如6月,或每月本身以及程序的名称,将显示所有他们正在玩该月的游戏。

I have a program that involves Javascript to allow for interaction with a webpage. It's a baseball site so what I am doing is prompting the user to enter a month. The user can enter a number, like 6 for June, or the name of the month itself and the program will display all the games they are playing that month.

我这样做的方法是创建一个数组,并将其与游戏信息存储。因此,七月份会是这个样子:

The way I did this was to create an array and store it with the game information. So the month of July would look something like this:

if(month == 7)    // July
{
    var gamesPlayed = ["7/1/16: Team1 @ Team2", "7/3/16: Team2 @ Team 4",
                       "7/4/16: Team3 @ Team2" , ... ,etc, ...];
}

在我的主要功能,我想打印阵列(即执行,当我按下提交按钮的那一个)。

In my main function (the one that executes when I push the Submit button), I want to print the array.

var schedule = getSchedule(July);

for(var i = 0; i < schedule.length; i++)
{
    document.getElementById("result").innerHTML = schedule[i] + "<br />";
}

有关某种原因,这是行不通的。它所做的一切它打印数组中的最后值,而不是整个事情。为什么它不打印整个数组?我试着做的document.write(附表[I] +&LT; BR /&gt;中); 并没有做什么,我想要的。它印,但它打印了一个页面上本身的地方,我不能一次在新的月份或返回到主页等有没有办法得到这个打印所有元素,而不只是最后一个?

For some reason this does not work. All it does it print the very last value in the array and not the whole thing. How come it is not printing the whole array? I tried to do document.write(schedule[i] + "<br />"); and that didn't do what I wanted. It printed it, but it printed it on a page by itself to where I couldn't time in a new month or go back to a homepage, etc. Is there a way to get this to print all the elements and not just the last one?

推荐答案

您可以使用。加入()的阵列组合成一个字符串,每个条目分开&LT; BR&GT;

You can use .join() to combine the array into one string, and separate each entry by <br>:

document.getElementById("result").innerHTML =
  schedule.join("<br>");

有没有需要自闭 / &LT; BR&GT; 。更重要的是,没有必要为循环。上面code会做这件事。

There's no need for the self-closing / in <br>. More important, there's no need for the for loop. That code above will do the whole thing.

如果你想有一个&LT; BR&GT; 最后一项记录后,只需添加:

If you want a <br> after the last entry, just add it:

document.getElementById("result").innerHTML =
  schedule.join("<br>") + "<br>";

这篇关于打印在单独一行JavaScript数组的每个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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