为什么让作用域说未在嵌套作用域中定义变量?

时间:2018-06-24 10:36:20

标签: javascript

我正在尝试运行以下代码:

function LCS(s1, s2) {
  let m = s1.length;
  let n = s2.length;

  let table = [];
  for (let i = 0; i <= m; i++) {
    table.push([]);
    for (let j = 0; j <= n; j++) {
      if (i === 0 || j === 0) {
        table[i][j] = 0;
      } else if (s1[i - 1] === s2[j - 1]) {
        // Both s1 and s2 have the same element on the previous index
        // so increase the length of common subsequence by 1 here
        table[i][j] = table[i - 1][j - 1] + 1;
      } else {
        table[i][j] = max(table[i - 1][j], table[i][j - 1]);
      }
    }
    // We've found the length here.
    let index = table[m][n];
    console.log(`The length of LCS between "${s1}" and "${s2}" is ${index}`);

    // Now to get the sequence we need to backtrack from the m, n th index back to start.
    let i = m;
    let j = n;
    let commonSubSeq = "";
    while (i > 0 && j > 0) {
      // If current character in both strings is same, then it is part of LCS.
      if (s1[i - 1] === s2[j - 1]) {
        commonSubSeq += s1[i - 1];
        i--;
        j--;
      } else if (table[i - 1][j] > table[i][j - 1]) {
        i--;
      } else {
        j--;
      }
    }
    return commonSubSeq
      .split("")
      .reverse()
      .join("");
  }
}

console.log(LCS("AGGTAB", "GXTXAYB"));

我遇到以下错误:

      if (i === 0 || j === 0) {
      ^

ReferenceError: i is not defined
    at LCS (C:\Users\LCS-new.js:9:7)

我不明白为什么该变量在嵌套作用域中不可用?

1 个答案:

答案 0 :(得分:1)

此答案“ 这是由于吊装而引起的” 不完整。 i引发ReferenceError的原因是由于吊起**。 JS之所以不在循环头(已声明i并将其分配给0)的标题中查找,是因为有两个不同的作用域。循环标题中的第一个,循环正文中的第二个(在括号{}之间)。

** let i = m;将在for循环的顶部声明变量i。由于letconst的“吊装”与所有其他类型的声明所使用的吊装不同,因此将 i声明为未分配。”

与声明时分配给var的{​​{1}}不同,让变量保持未分配