繁体   English   中英

Javascript 变量范围混淆

[英]Javascript variabel scope confusion

我有一个关于范围的小问题。 在下面的程序中,我在 .js 文件中声明了两个变量,countRows 和 countCols。 saveTable()里面。 但是,当我记录它们时,它们的值在函数之后为 0。

为什么他们不从函数中保留它们的价值?

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

要添加到@Steven Stark 的答案中,发生这种情况是因为您在记录变量之前没有调用该函数,它们在此处共享范围。 下面的例子:

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

您可以获得有关闭包的更多信息(这里超出了主题),但很有趣: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

您必须调用该函数

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM