Javascript:在数组之前未定义

时间:2015-04-13 00:01:47

标签: javascript

我遇到了一些代码,我正在使用javascript编写代码,该代码应该返回一个包含月份列和利润列的表。一切都没问题,除非我似乎无处可去。这是代码:

"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>');

未定义的值出现在第一个文档写入之前,就好像我正在调用空变量的值。

3 个答案:

答案 0 :(得分:3)

这是因为你是document.writing一个函数,由于Javascript的规则,它会隐式返回undefined。这个函数的内部是你真正想要的document.writes。尝试:

"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>');

小提琴:https://jsfiddle.net/zsh18999/

答案 1 :(得分:1)

你应该写:

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

答案 2 :(得分:1)

调用document.write(Fventes(mois, ventes));实际上会写"undefined",因为调用Fventes(mois, ventes)会返回undefined。你应该写:

"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>');