省略分号时出错-有人可以解释为什么吗?

问题描述 投票:0回答:2

有人可以解释为什么如果我在while(nums[right-1] == nums[right--]);行中省略分号会导致语法错误吗?我通常理解分号的要点,但是为什么要使用此特定行而不是其他行?

var threeSum = function(nums) {
    nums.sort((a,b)=>a-b);
    let result = [];
    for (let i=0;i<nums.length;i++) {
        let t = -nums[i];
        let left = i+1, right = nums.length-1;
        while(left < right) {
            if (nums[left] + nums[right] == t) {
                result.push([nums[i], nums[left], nums[right]]);
                while(nums[left+1] == nums[left++]);
                while(nums[right-1] == nums[right--]);
            } else if (nums[left]+nums[right] < t) left++;
            else right--;
        }
        while(nums[i+1]==nums[i]) i++
    }

    return result;

};
javascript compiler-errors automatic-semicolon-insertion
2个回答
1
投票

循环需要一些循环。基本上是语句或代码块。例如:

while (something) {
  this.isInACodeBlock();
}

或:

while (something)
  this.isAStatement();

请记住,声明可以是无操作。分号本身就可以达到这个目的。由于回车与语言无关,因此这是一个循环,包含以下语句:

while (something);

走出一步,此循环是内部一个代码块,该代码块在循环之后立即结束:

if (somethingElse) {
  while (something)
}

如果在while循环之后仅存在一条语句,那么即使该行为是意外的或错误的,它在语法上也是正确的。但是有一个大括号。

因此,解释器期望一个语句或一个开始块,但是遇到一个结束块。这是一个错误。


0
投票

@ David的很好的解释,我要补充一点,为避免这些错误,您应该考虑遵循类似airbnb的样式指南。使您的代码更易于阅读。

实现该目标的方法:将++替换为+=。注释代码的主要部分...等等

好的代码是您可以通过阅读理解的代码。我应该已经了解threeSums函数的作用,以及为什么只看一下就执行论文while

// the function do blabla
function threeSums(nums) {
  nums.sort((a, b) => a - b);

  const result = [];

  for (let i = 0; i < nums.length; i += 1) {
    // what is t?
    const t = -nums[i];

    let left = i + 1;
    let right = nums.length - 1;

    while (left < right) {
      // what is the case covered by this if?
      if (nums[left] + nums[right] == t) {
        result.push([
           nums[i],
           nums[left],
           nums[right],
        ]);

        while (nums[left + 1] == nums[left]) {
          left += 1;
        }

        while (nums[right - 1] == nums[right]) {
          right -= 1
        }
      } else if (nums[left] + nums[right] < t) {
        left += 1;
      } else {
        right -= 1;
      }
    }

    while (nums[i + 1] == nums[i]) {
      i += 1;
    }
  }

  return result;
};
© www.soinside.com 2019 - 2024. All rights reserved.