0
var tmu, categories = [['Morning','am'],['Evening','pm']], 
days = ['mon', 'tue', 'wen', 'thu', 'fri', 'sat', 'sun'],
fullDay, i;

tmu += '<table>';

categories.forEach(function(ele){ 
tmu += '<tr id="periodTitle">';
tmu += '<td colspan=7 style="text-align:center;">'+ele[0]+'</td>';
tmu += '</tr>';
for(i = 0; i <= 6; i++){
tmu += '<td id="'+days[i]+'-'+ele[1]+'">x</td>';    
}        
});
tmu += "</table>";
console.log(tmu);

I am trying to write some code to loop through some table creation however it keeps adding an undefined text to the beginning of the loop and I'm not sure why, everything else works great. Any ideas on how this could happen?

The fiddle link is here. Thanks for any help in advance!!

4 Answers 4

2

This will fix it:

var tmu = '';

As you are declaring the variable but not assigining a value, tmu will be undefined and when you do tmu += '<table>';, tmu will be coerced to a string - i.e. undefined.

Sign up to request clarification or add additional context in comments.

Comments

0

initialize tmu as string see the example

**var tmu=''**, categories = [['Morning','am'],['Evening','pm']], 
days = ['mon', 'tue', 'wen', 'thu', 'fri', 'sat', 'sun'],
fullDay, i;

tmu += '<table>';

categories.forEach(function(ele){ 
    tmu += '<tr id="periodTitle">';
    tmu += '<td colspan=7 style="text-align:center;">'+ele[0]+'</td>';
    tmu += '</tr>';
    for(i = 0; i <= 6; i++){
    tmu += '<td id="'+days[i]+'-'+ele[1]+'">x</td>';    
    }        
});
    tmu += "</table>";
   console.log(tmu);

Comments

0

You need to remove the + in the following rule:

tmu += '<table>';

Change the rule to this and the undefined is gone:

tmu = '<table>';

Comments

0

When you use tmu for the first time, use a simple assignment

tmu = '<table>';

Right now your instruction tmu += '<table>' is a shortcut for tmu = tmu + '<table>': so, you are doing a string concatenation and your tmu variable on the right side of this assignment will be evaluated as a string, which value has to be undefined, since no previous assignment was done.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.