Reputation: 1278
I'm making a JavaScript table from scratch. I'm trying to print out a series of values from an array - these would be the table heads, but for this question I have them as paragraphs.
There should be four values, but five values end up being printed. The first value comes out "undefined," but the other four values print out as intended. Here is the code:
<div id="test"></div>
<script>
var headArray = ["Artist", "Album", "Year", "Genre"];
var tableHead = function() {
var str;
for (var i = 0; i < headArray.length; i++) {
str == "";
str += '<p>';
str += headArray[i];
str += '</p>';
console.log(str);
}
return str;
}
var x = document.getElementById('test');
x.innerHTML = tableHead();
</script>
When the HTML is run the document shows: undefined Artist Album Year Genre.
The console.log shows:
"undefined<p>Artist</p>"
"undefined<p>Artist</p><p>Album</p>"
"undefined<p>Artist</p><p>Album</p><p>Year</p>"
"undefined<p>Artist</p><p>Album</p><p>Year</p><p>Genre</p>"
How can I prevent and/or remove undefined values from printing in the DOM? Keep in mind this is just the first part of a larger project (I am building a table after all).
Upvotes: 1
Views: 4304
Reputation: 12815
The reason for "undefined" in your console.log() is that you never initialized str
. In the first line of your for
loop, you have str == ""
. This is a comparison of the value of str
to an empty string. Because str
was not initialized, the return of that is undefined
.
It would appear that you're trying to initialize your variable, but that should be done outside of your for loop. If you change from str == ""
to str = ""
and look at your <div id="test"></div>
after this code runs, you'll only see the result of the last iteration. This is because you are setting str
to a new string every pass.
This is what you'll need to do. With this code, your console.log will always return the previous iterations as well. Otherwise your end-result table will only have the last header cell:
var headArray = ["Artist", "Album", "Year", "Genre"];
var tableHead = function() {
var str = '';
for (var i = 0; i < headArray.length; i++) {
str += '<p>';
str += headArray[i];
str += '</p>';
console.log(str);
}
return str;
}
var x = document.getElementById('test');
x.innerHTML = tableHead();
Upvotes: 6
Reputation: 63570
You need to have str
declared outside the loop or it will keep getting rewritten (as well as changing that ==
to a =
:
var tableHead = function() {
var str = "";
for (var i = 0; i < headArray.length; i++) {
str += '<p>';
str += headArray[i];
str += '</p>';
}
return str;
}
Upvotes: 3
Reputation: 20229
Change
str == "";
to
str = "";
And initialize the variable str outside the loop
var str="";
Upvotes: 0