拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 如果为真,很难理解如何停止回圈

如果为真,很难理解如何停止回圈

白鹭 - 2022-03-02 1994 0 0

这是我在这里的第一篇文章,我正在尝试做一个 freecodecamp 练习。

这是我的代码:

function mutation(arr) {
  let newArr = arr[0].toLowerCase();
  let arrNew = arr[1].toLowerCase();
  let test = newArr.split(' ');
  let newTest = arrNew.split(' ');

  for (let i=0; i < test.length; i  ) {
    for (let j=0; j < newTest.length; j  ) {
      if (newTest[j] === test[i]) {
        return true;
      }
    }
  }
  return false;
}

mutation(["hello", "hey"]);

练习是“突变”,如果阵列中的第一个字符串包含第二个字符串中的所有字母,我需要回传 true。我试图了解如何在 if 陈述句为真时停止回圈并保存它。

提前致谢,如果我没有正确解释自己,我很抱歉。

uj5u.com热心网友回复:

以下代码应该对您有所帮助。

function mutation(arr) {
    let newArr = arr[0].toLowerCase();
    let arrNew = arr[1].toLowerCase();
  
    for (let i=0; i < newArr.length; i  ) {
        if (arrNew.indexOf(newArr[i]) == -1) {
            return false;
        }
    }
    return true;
}

mutation(["hello", "hey"]);

不需要使用阵列。在 JS 中,字符串就像阵列一样作业,我们可以使用“for”回圈。

uj5u.com热心网友回复:

对于你的问题

return将退出函式,因此将退出回圈。由此
我们知道,如果您的函式回传false,则该条件newTest[j] === test[i]从未得到验证。

练习的提示

您可以假设第一个单词包含第二个单词的所有字母,就像您现在所做的那样迭代并检查是否找到反例!

uj5u.com热心网友回复:

如果您想在示例代码中使用回圈,这里是一种非常冗长的方法:

function mutation(arr) {
  let hasAllLetters = true;
  let stringToCompare = arr[0].toLowerCase();
  let referenceString = arr[1].toLowerCase();
  let hasCurrentLetter;
  
  for (let i=0; i < referenceString.length; i  ) {
    hasCurrentLetter = false;
    
    for (let j=0; j < stringToCompare.length; j  ) {
        
      if (referenceString[i] === stringToCompare[j]) {
        hasCurrentLetter = true;
        
        // break from the second loop as soon as the condition is satisfied
        break;
      }
    }
        
    if(!hasCurrentLetter){
      hasAllLetters = false;
      // as soon as there is at least one letter which does not exist from the reference string
      // break from the second loop and exit yielding the result false
      break;
    }
  }
  
  return hasAllLetters;
}

let res;

res = mutation(["hello", "goll"]);
console.log("res: ", res); // false

res = mutation(["hello", "olhh"]);
console.log("res: ", res); // true

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *