代码之家  ›  专栏  ›  技术社区  ›  ayushgp

为什么让作用域说变量没有在嵌套作用域中定义?[副本]

  •  0
  • ayushgp  · 技术社区  · 6 年前

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

    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 回复  |  直到 6 年前
        1
  •  1
  •   leonardofed    6 年前

    这个答案” 这是因为吊装” 是不完整的。为什么 i 抛出由于提升**而发生的引用错误。js不在循环头中的原因(在 已申报并转让给 0 )是因为有两个不同的作用域。循环头中的第一个,循环体中的第二个(在括号{}之间)。

    ** let i = m; 将声明变量 在for循环的顶部。因为“吊装” let const 不同于所有其他类型的声明所使用的提升, 将被宣布为未分配。`

    不像 var 分配给 undefined 声明时,让变量保持不变。 未分配 是的。