【问题标题】:JavaScript - If statement inside a loop issuesJavaScript - 循环内的 If 语句问题
【发布时间】:2018-03-24 13:06:36
【问题描述】:
function rot13(str) { 

var yahoo = [];

for (var i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) > 64 && str.charCodeAt[i] < 91){continue;}{
        var cnet = str.charCodeAt(i);
        yahoo.push(cnet);
    } else {
      var j = str.charCodeAt(i);
        yahoo.push(j);
    }
}

var ugh = yahoo.toString();
return ugh;
}

rot13("SERR PBQR PNZC");

尝试在 for 循环中使用 if else 语句并遇到 else 语句的一些问题(获取“语法错误:意外标记 else”)。现在的主要目标是尝试在传递其他字符(即空格、感叹号等)的同时操作字符串字母字符。当然有一种更简单的方法可以做到这一点,但真的只是想知道在循环中编写 if else 语句有什么问题以及我哪里出错了。感谢帮助

【问题讨论】:

  • 继续在那里做什么?
  • 如果条件 {continue;} 之后您有额外的块
  • 代码返回一个空字符串,没有中断或继续
  • @Bobbygllh 很好,代码没有做 anything 因为它有语法错误;它根本不会运行。
  • 我知道,应该说“当我删除 else 语句时返回一个空字符串”

标签: javascript for-loop if-statement


【解决方案1】:

if 之后有 两个 代码体:

if (str.charCodeAt(i) > 64 && str.charCodeAt[i] < 91)
  {continue;}   // actual body of the if

  { // just a random block of code
    var cnet = str.charCodeAt(i);
    yahoo.push(cnet);
  }

第二个根本不是if 的一部分,因为您只能获得if一个 代码块。这就是为什么else 是“意外的”。

【讨论】:

  • 这完全有道理。我有 continue 的原因是它返回了一个没有它的空字符串(在删除 else 语句以便它可以运行之后)
【解决方案2】:

您在完成 if 语句后尝试调用语句。您的if 会生成continue;,然后在调用else 之前执行其他操作。尝试重构continue;。它与for循环没有任何关系:)

【讨论】:

    【解决方案3】:

    尝试在 for 循环中使用 if else 语句并遇到 else 语句的一些问题(获取“语法错误:意外标记 else”)。

    但真的只是想知道在循环中编写 if else 语句有什么问题以及我哪里出错了

    您不编写if..else 语句,而是编写if 语句和尝试添加else 语句的代码块;而这个 else 语句在那里没有意义。

    您的代码如下所示:

    //this is your condition
    if (str.charCodeAt(i) > 64 && str.charCodeAt[i] < 91){
        continue;
    }
    
    //and this is an anonymous code block; anonymous, because you could name it
    {
        var cnet = str.charCodeAt(i);
        yahoo.push(cnet);
    
    //and such code-blocks have no `else`,
    //that's why you get the error, 
    //this else doesn't belong to the condition above
    } else {
        var j = str.charCodeAt(i);
        yahoo.push(j);
    }
    

    您的问题是 {continue;} 部分将您的块的整个含义更改为我所描述的


    当然有更简单的方法

    是的,您可以使用 String#replace,并将字母 a-m 替换为 n-z,反之亦然

    //a little helper
    const replace = (needle, replacement) => value => String(value).replace(needle, replacement);
    
    //the definition of `rot13` as a String replacement
    const rot13 = replace(
      /[a-m]|([n-z])/gi, 
      (char,down) => String.fromCharCode(char.charCodeAt(0) + (down? -13: 13))
    );
    
    let s = "SERR PBQR PNZC";
    console.log("input: %s\noutput: %s", s, rot13(s));

    解释:match[0] 总是包含整个匹配的字符串,这里是char;我在[n-z] 周围添加了一个组,这样match[1] 又名。 down 在字符为 n-z 时填充,但在字符为 a-m 时不填充。

    因此我知道,如果down被填满,我必须做char.charCodeAt(0) - 13否则char.charCodeAt(0) + 13

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-02
      • 2015-04-21
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多