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() {
// ...
}