【问题标题】:code is not bypassing first "if" statement代码没有绕过第一个“if”语句
【发布时间】:2021-11-04 19:16:26
【问题描述】:

有人可以提供关于为什么我的代码没有绕过第一个“if”语句的见解吗?我正在编写应该创建密码的代码。如果字母的 unicode 不大于 97 或小于 122,则应该按原样简单地推送 unicode。

// Write class below
class ShiftCipher{
  constructor(shift){
    this._shift = shift;
  }
  encrypt(str){
    let newStr = str.toLowerCase();
    let strArr = [];
    let newStrArry = [];
    let extraNum = 0;
    let bigArr = [strArr, newStrArry]
    for(let i = 0; i < newStr.length; i++){
      strArr.push(newStr.charCodeAt(i));
      if(newStr.charCodeAt(i) > 97 || newStr.charCodeAt(i) < 122) {
        if(newStr.charCodeAt(i)+this._shift > 122){
          extraNum = (newStr.charCodeAt(i)+this._shift) - 122;
          extraNum += newStrArry.push(96+extraNum);
          console.log('a');
          } else {
          newStrArry.push(newStr.charCodeAt(i)+this._shift);
          console.log('b');
          console.log(newStr[i]);
          }
      } else {
        newStrArry.push(newStr.charCodeAt(i));
        console.log('c');
      }
    }
    return bigArr;
  }
}
const mySymbol = new ShiftCipher(4);
console.log(mySymbol.encrypt('<3'));

【问题讨论】:

  • 这段代码是你写的吗?您是否尝试调试它?例如,要重现 if 语句正在检查的内容,您可以简单地在 Javascript 控制台中运行 '&lt;'.charCodeAt(0)
  • "不大于 97 或小于 122" - 但它反过来检查? “如果大于 97 或小于 122”。如果其中任何一个为真,它将运行代码

标签: javascript arrays if-statement conditional-statements


【解决方案1】:

每个可能的数字都满足条件newStr.charCodeAt(i) &gt; 97 || newStr.charCodeAt(i) &lt; 122(即任何不大于 97 的数字必须小于 122)。因此,没有任何输入会出现在您的 else 子句中。

我假设您希望 if 条件只接受 97 到 122 之间的 unicode。如果是这种情况,那么您需要将条件更改为newStr.charCodeAt(i) &gt; 97 &amp;&amp; newStr.charCodeAt(i) &lt; 122

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    相关资源
    最近更新 更多