indexOf() 与 for 循环

indexOf() with for loop

我正在尝试检查数组的第一个元素是否包含数组第二个元素的所有字母。但它不能在这个给定的属性上正常工作。我找不到哪里做错了?

function mutation(arr) {
  var first = arr[0].toLowerCase();
  var second = arr[1].toLowerCase();
  
    for(i = 0; i<second.length; i++){
     return first.indexOf(second[i]) !== -1 ? true : false;
    }


}

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

您使用的条件不正确。您应该检查第二个元素的所有字符是否都包含在第一个元素中。因此,您必须检查在第一个元素上为第二个元素字符 returns 的每个字符调用的 indexOf 是否为真。如果是这样,那么第二个元素的所有字符确实都包含在第一个元素中。否则为假。

你可以试试这个:

function mutation(arr) {
    var first = arr[0].toLowerCase();

    // we use split to get an array of the characters contained in the second element
    var second = arr[1].toLowerCase().split('');
   
    return second.every(character=>first.indexOf(character)>-1)
}

console.log(mutation(["hello", "hey"]));
console.log(mutation(["hello", "heo"]));