Javascript 如何使用其他函数变量?

Javascript 如何使用其他函数变量?,javascript,global,Javascript,Global,如何在genTable中使用a?它表示未定义a JS: function colNum(){ a=prompt(' The number of columns?'); if(!parseInt(a)) { console.log("Not number") } } function genTable() { table = document.createElement('table'); table.setAttribute('

如何在
genTable
中使用
a
?它表示未定义
a

JS:

function colNum(){
    a=prompt(' The number of columns?');

    if(!parseInt(a))
    {
        console.log("Not number")
    }
}

function genTable() {
    table = document.createElement('table');
    table.setAttribute('id','tbl');
    tr = document.createElement('tr'); 

    for (var i = 0; i < a; i++)
    {
        var th1 = document.createElement('th');
        var text1 = document.createTextNode(i);
        th1.appendChild(text1);
        tr.appendChild(th1);
    }

    table.appendChild(tr);
    document.body.appendChild(table);
}
函数colNum(){
a=提示(‘列数?’);
如果(!parseInt(a))
{
控制台日志(“非编号”)
}
}
函数genTable(){
table=document.createElement('table');
table.setAttribute('id','tbl');
tr=document.createElement('tr');
对于(变量i=0;i
HTML


genTable
中使用
a

  • genTable
    一个参数,并从
    colNum

    // in function colNum
        genTable(a); // a refers to the variable named a
    // ...
    
    function genTable(a) {
        // a refers to the parameter named a
    }
    
  • var-a在一个包含
    colNum
    genTable
    的闭包中,并且在后代闭包中不使用
    var
    (您当前根本没有使用
    var

  • 目前您已经可以访问它,但这是因为您还没有
    var
    d它,这是一个不好的习惯,因为它可能会在将来的代码中导致标识符冲突

    // in function colNum
        genTable(a); // a refers to the variable named a
    // ...
    
    function genTable(a) {
        // a refers to the parameter named a
    }
    
    var a;
    function colNum() {
        // ...
    }
    function genTable() {
        // ...
    }