本文介绍了函数式如何嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习函数式编程,完全摆脱 code> 或和一个合适的字符串函数:

  function isIsogram (string){
string = string.toLowerCase(); //不区分大小写
return string.split('')。every(function(character,index){
return!string.includes(character,index + 1);
});

而不是您可能也使用了。


I'm in the process of learning functional programming, and completely getting rid of for loops has been a challenge sometimes, because they provide so much control and freedom. Below is an example of checking if a string is an isogram or not (no letters should be repeated). With nested for loops, it became an easy solution. Is there a way to do this the functional way with any high order functions or anything else? Any suggestion would be a huge help.

Code:

function isIsogram(string) {
  let array = string.split('');
  let condition = true;
  for (let i = 0; i < string.length; i++) { //first loop picks character
    for (j = i + 1; j < string.length; j++) { //second loop compares it rest
      if (array[i].toLowerCase() == array[j].toLowerCase())
        condition = false; //if repeat, the condition false
    }
    return condition;
  }
}
解决方案

You can use every or some together with a suitable string function:

function isIsogram(string) {
    string = string.toLowerCase(); // case insensitive
    return string.split('').every(function(character, index) {
        return !string.includes(character, index+1);
    });
}

Instead of includes you might also have utilised indexOf.

这篇关于函数式如何嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:00
查看更多