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] + "
";
}
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] + "
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?
"];
They will print on subsequent lines if logging is done in the loop. If you wish to print an array of numbers in one line, you can use array.join[', ']
var array = [0,1,1,2,3,5,8,13,21,34,55];
var str = array.join[', '];
console.log[str];
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
You could also build an output format in the loop by concatenation:
str = "";
for [var i=0; i "John"
> "James"
Now sometimes you want the elements to be printed in a nice format to a web page. You can do
so by assigning the array as the innerHTML
property of an element.
Here’s an example:
JavaScript print array
let arr = ["Jack", "John", "James"];
document.getElementById["arrPrint"].innerHTML = arr;
But when you have an array of objects, the innerHTML
of the element will be set as [object Object]
instead of the array elements. To print an array of objects properly, you need to format the array as a JSON string using JSON.stringify[]
method and attach the string to a tag in your HTML page.
Try the following example:
JavaScript print array
let arr = [{name: "Jack"}, {name: "John"}, {name: "James"}];
document.getElementById["arrPrint"].innerHTML = JSON.stringify[arr, null, 2];
Your array will be printed as follows:
[
{
"name": "Jack"
},
{
"name": "John"
},
{
"name": "James"
}
]
And that’s how you can print JavaScript array elements to the web page.
How do I print an array on separate lines?
How do you split an array in JavaScript?
How do you print an array in JavaScript?
tag in your HTML page. And that's how you can print JavaScript array elements to the web page.