0

i'm having trouble with a little code i'm writing in javascript which is supposed to return a table with a column for month and a column for profits. Everything is okay except it seems that i got a undefined value out of nowhere. Here's the code :

"use strict";

var i, mois, ventes, a, b;
mois=["Janvier","Fevrier","Mars","Avril","Mai","Juin","Juillet","Aout","Septembre","Octobre","Novembre","Decembre"];
ventes=[120,500,350,400,600,890,450,100,250,300,650,450];

function Fventes(a, b) {
    for (i=0; i<12; i++) {
    document.write('<tr><td>', a[i],'</td><td>',b[i],'</td></tr>');
    }
}
document.write('<table><thead><td>Tableau des ventes</td></thead><tbody>');
document.write(Fventes(mois, ventes));
document.write('</tbody></table>');

The undefined value appears before the 1st document write, as if i was calling the value of an empty variable.

1
  • 1
    Try to avoid document.write and consider using DOM Methods instead; i.e. parent_node.appendChild(table_root_node) Commented Apr 13, 2015 at 0:10

3 Answers 3

3

It's because you're document.writing a function, which returns undefined implicitly due to the rules of Javascript. Inside of that function are the document.writes you really wanted. Try:

"use strict";

var i, mois, ventes, a, b;
mois=["Janvier","Fevrier","Mars","Avril","Mai","Juin","Juillet","Aout","Septembre","Octobre","Novembre","Decembre"];
ventes=[120,500,350,400,600,890,450,100,250,300,650,450];

function Fventes(a, b) {
    for (i=0; i<12; i++) {
        document.write('<tr><td>', a[i],'</td><td>',b[i],'</td></tr>');
    }
}
document.write('<table><thead><td>Tableau des ventes</td></thead><tbody>');
Fventes(mois, ventes);
document.write('</tbody></table>');

Fiddle: https://jsfiddle.net/zsh18999/

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

Comments

1

you should write:

document.write('<table><thead><td>Tableau des ventes</td></thead><tbody>');
Fventes(mois, ventes);
document.write('</tbody></table>');

Comments

1

Calling document.write(Fventes(mois, ventes)); actually writes "undefined" because calling Fventes(mois, ventes) return undefined. you should write:

"use strict";

var i, mois, ventes, a, b;
mois=["Janvier","Fevrier","Mars","Avril","Mai","Juin","Juillet","Aout","Septembre","Octobre","Novembre","Decembre"];
ventes=[120,500,350,400,600,890,450,100,250,300,650,450];

function Fventes(a, b) {
    for (i=0; i<12; i++) {
    document.write('<tr><td>', a[i],'</td><td>',b[i],'</td></tr>');
    }
}
document.write('<table><thead><td>Tableau des ventes</td></thead><tbody>');
Fventes(mois, ventes);
document.write('</tbody></table>');

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.