JavaScript检查字符串中是否包含字母

时间:2020-08-04 05:24:00

标签: javascript

我具有以下JavaScript函数,我想使用该函数检查名为mutation的数组的 first 元素是否包含第二个元素的所有字母。

function mutation(arr) {
  let test    = arr[1].toLowerCase();
  let target  = arr[0].toLowerCase();

  let split = test.split('');

  split.forEach((elem)=>{
    if(target.indexOf(elem) < 0 ) {
      return false;
    }
  });
  return true;
}

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

现在它应该向我显示布尔值false,因为你好单词中不存在字母 y 。但事实并非如此。

我在做错什么吗?

5 个答案:

答案 0 :(得分:3)

您可以使用Array.prototype.every()

function mutation(arr) {
  let test = arr[1].toLowerCase();
  let target = arr[0].toLowerCase();
  let split = test.split('');
  return split.every(x => target.includes(x)); // checks if all letters of `split` exists in `target`
}
console.log(mutation(["hello", "hey"]));
console.log(mutation(["hello", "heo"]));
console.log(mutation(["helloworld", "lloword"]));

答案 1 :(得分:1)

您可以尝试另一种方法以获得预期的结果:

function mutation(arr) {
  let test    = arr[1].toLowerCase().split('').join('');
  let target  = arr[0].toLowerCase().split('').join('');
  return target.includes(test);
}

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

答案 2 :(得分:1)

我会做的:

function mutation(arr) {
  let test    = arr[1].toLowerCase();
  let target  = arr[0].toLowerCase();
  return target.includes(test);
}

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

答案 3 :(得分:0)

ForEach中的Return语句不会从函数中返回,您可以使用简单的for循环或reduce来在线获取最终结果

function mutation(arr) {
  let test    = arr[1].toLowerCase();
  let target  = arr[0].toLowerCase();

  let split = test.split('');

  const result = split.reduce((acc, curr) => acc && target.includes(curr), true);

  return result;
}

console.log(mutation(['hello', 'y']));

答案 4 :(得分:0)

坚持使用更经典的方法:

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

function mutation(args) {
  const target  = args[0].toLowerCase();
  const test    = args[1].toLowerCase();
  
  for(let i = 0; i < test.length; i += 1) {
  
    if (target.indexOf(test[i]) < 0) {
      return false;
    }
    
  }
  return true;
}

相关问题