indexOf() :有没有更好的方法来实现这个?

indexOf() : is there a better way to implement this?

编辑

谢谢你们,对于我的问题没有更具体,我深表歉意。 编写此代码是为了检查第二个字符串中的字符是否在第一个字符串中。如果是这样,它将 return 为真,否则为假。

所以我的代码有效,我知道的很多,但我肯定有更好的方法来实现它。

请记住,这是来自 Freecodecamp 的 Javascript 树的编码挑战。

这是我的代码:

function mutation(arr) {

  var stringOne = arr[0].toLowerCase();
  var stringTwo = arr[1].toLowerCase().split("");
  var i = 0;
  var truthyFalsy = true;

  while (i < arr[1].length && truthyFalsy) {

    truthyFalsy = stringOne.indexOf(stringTwo[i]) > -1;
    i++

  }
  console.log(truthyFalsy);
}




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

一定有更好的方法来做到这一点。我最近学习了 map 函数,但不确定如何使用它来实现它,最近还学习了一个 Array.prototype.every() 函数,我今晚将阅读它。

建议?想法?

问题很含糊。但是我从代码中了解到,您需要检查两个字符串之间的字符串匹配。

既然你知道它的两个字符串,我就把它们作为两个参数传递。另外,我会将 while 更改为 for 语句并添加 break/continue 以避免使用变量 get 和 set。

请注意,在最坏的情况下它几乎是相同的,但在最好的情况下它的计算时间只有一半。

mutation bestCase 14.84499999999997
mutation worstCase 7.694999999999993
bestCase: 5.595000000000027
worstCase: 7.199999999999989

// your function (to check performance difference)
function mutation(arr) {

  var stringOne = arr[0].toLowerCase();
  var stringTwo = arr[1].toLowerCase().split("");
  var i = 0;
  var truthyFalsy = true;

  while (i < arr[1].length && truthyFalsy) {

    truthyFalsy = stringOne.indexOf(stringTwo[i]) > -1;
    i++

  }
  return truthyFalsy;
}



function hasMatch(base, check) {
  var strOne = base.toLowerCase();
  var strTwo = check.toLowerCase().split("");

  var truthyFalsy = false;

  // define both variables (i and l) before the loop condition in order to avoid getting the length property of the string multiple times.
  for (var i = 0, l = strTwo.length; i < l; i++) {
    var hasChar = strOne.indexOf(strTwo[i]) > -1;
    if (hasChar) {
      //if has Char, set true and break;
      truthyFalsy = true;
      break;
    }
  }
  return truthyFalsy;
}

var baseCase = "hello";
var bestCaseStr = "hey";
var worstCaseStr = "yap";

//bestCase find match in first iteration
var bestCase = hasMatch("hello", bestCaseStr);
console.log(bestCase);

//worstCase loop over all of them.
var worstCase = hasMatch("hello", worstCaseStr);
console.log(worstCase);

// on your function
console.log('mutation bestCase', checkPerf(mutation, [baseCase, bestCaseStr]));

console.log('mutation worstCase', checkPerf(mutation, [baseCase, worstCaseStr]));

// simple performance check
console.log('bestCase:', checkPerf(hasMatch, baseCase, bestCaseStr));

console.log('worstCase:', checkPerf(hasMatch, baseCase, worstCaseStr));

function checkPerf(fn) {
  var t1 = performance.now();
  for (var i = 0; i < 10000; i++) {
    fn(arguments[1], arguments[2]);
  }
  var t2 = performance.now();
  return t2 - t1;
}