为什么我的 while 循环没有完全迭代

Why is my while loop not iterating through completely?

本文关键字:迭代 我的 while 循环 为什么      更新时间:2023-09-26

所以这是我下面的代码,这个程序的目标是检查是否可以在第一个字符串中找到第二个字符串的字母。然而,我发现问题并非如此,价值增加。所以循环只经过一次。因此,该程序在它找到并返回 true 的第一个字母处结束。如何让 i 增加,以便它遍历字符串的每个字符?

function mutation(arr) {
  var str = arr[1];
  str = str.toLowerCase().split("");
  var i = 0;
  while (i < arr.length) {
    if (arr[0].indexOf(str[i]) > -1) {
      //return  arr[i].indexOf(str[i], i);
      return true;
    } else {
      return false;
    }
    i++;
  }
}
mutation(["hello", "hey"]);
也许吧

function mutation(arr) {
  var str = arr[1];
  str = str.toLowerCase().split("");
  // iterating an array screams "for loop"
  for (var i=0; i < str.length; i++) {
    // if the letter was not found exit immediately
    if (arr[0].indexOf(str[i]) == -1) return false;
  }
  // since it didn't exit before, all the letters must have been found.
  return true;
}
function mutation(arr) {
  var base = arr[0],
      str = arr[1].toLowerCase().split(''),
      i = 0,
      match = true;
  while (i < str.length) {
    // if any target letter is not in base, return false
    if(base.indexOf(str[i]) === -1){
        return false;
    }
  }
  // otherwise they were all in, so return true
  return true;
}
mutation(["hello", "hey"]);

完全不同的技术。

此函数将第二个字符串中的所有字母替换为空格。 如果长度为零,则找到所有字母。

function mutation(arr) {
  return arr[1].replace(new RegExp("[" + arr[0] + "]", "g"), "").length == 0;
}