问题:
I have a small problem with regards to scope. In the program below I have declared two variables in the .js file, countRows and countCols. Inside the saveTable(). However t...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I have a small problem with regards to scope. In the program below I have declared two variables in the .js file, countRows and countCols. Inside the saveTable()
. However their value is 0 when after the function when I log them.
Why do they not hold their value from the function?
var table = document.getElementById("table");
var countRows = 0;
var countCols = 0;
function saveTable() {
countRows = table.rows.length;
countCols = table.rows[0].cells.length;
var data = "";
for(var i = 0; i < table.rows.length; i++) {
for(var j = 0; j < table.rows[i].cells.length; j++) {
data += table.rows[i].cells[j].innerHTML + ",";
}
}
document.cookie = data;
}
console.log(countRows); //These equal 0
console.log(countCols);
回答1:
To add to @Steven Stark answer, it happens because you didn't call the function before logging the variable, they share the scope here. Example below:
let a = 0;
// This change a, because the function is directly accessing the a declared in the parent scope
function changeA() {
a = 3;
}
changeA();
console.log(a)
// This doesn't change a
function changeAParameter(a) {
// because this 'a' only exists in the scope of this function
a = 5;
}
changeAParameter(a);
console.log(a);
You can have more information about closure (which is beyond topic here), but is interesting: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
回答2:
You have to invoke the function
var table = document.getElementById("table");
var countRows = 0;
var countCols = 0;
function saveTable() {
countRows = table.rows.length;
countCols = table.rows[0].cells.length;
var data = "";
for(var i = 0; i < table.rows.length; i++) {
for(var j = 0; j < table.rows[i].cells.length; j++) {
data += table.rows[i].cells[j].innerHTML + ",";
}
}
document.cookie = data;
}
// Call the function
saveTable();
console.log(countRows); //These equal 0
console.log(countCols);