Javascript variabel范围混淆

时间:2019-03-07 22:20:56

标签: javascript

关于范围,我有一个小问题。在下面的程序中,我在.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);

2 个答案:

答案 0 :(得分:1)

要添加到@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

答案 1 :(得分: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;
}
// Call the function
saveTable();
console.log(countRows); //These equal 0
console.log(countCols);