Javascript variabel scope confusion

问题: 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);
  • 发表于 2019-03-09 03:48
  • 阅读 ( 143 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除