54

2分钟编程技巧:不要在代码中使用循环

 5 years ago
source link: http://www.techug.com/post/2-minutes-of-programming-dont-use-loop.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
AfqmiiB.png!web

您应该使用像map、filter和reduce这样的函数,而不是编写for或while循环。这是个推荐做法,因为:

  • 循环使产生代码副作用变得容易,而副作用就会使代码逻辑变成意大利面条,杂乱无章。
  • 当你试图同时做不止一件事情时,循环会你陷入痛苦。
  • 函数式编程可以防止代码产生与感冒药一样多的副作用。它迫使你一次只做一件事,而且比循环更具可读性。

循环,就像指针一样,是一种简单的编程方法。它们对于某些关键代码非常有用,但我想会说,我们中很少有人在研究显卡驱动程序。

让我们切入正题——这里有一个JavaScript程序的比较。首先,老旧的循环版本:

const cats = ['Antonio', 'Squid', 'Tornado', 'Avocado', 'Barnacles', 'Abroteus'];

const stringStartsWithA = x => x[0].toLowerCase() === 'a';

const catsWhoseNameStartsWithA = [];

for (let i = 0; i < cats.length; i++) {
  if (stringStartsWithA(cats[i])) {
    catsWhoseNameStartsWithA.push(cats[i]);
  }
}

console.log(catsWhoseNameStartsWithA);

// Output:
// ["Antonio", "Avocado", "Abroteus"]

下面是新式的函数式编程:

const cats = ['Antonio', 'Squid', 'Tornado', 'Avocado', 'Barnacles', 'Abroteus'];

const stringStartsWithA = x => x[0].toLowerCase() === 'a';

const catsWhoseNameStartsWithA = cats.filter(stringStartsWithA);

console.log(catsWhoseNameStartsWithA);

// Output:
// ["Antonio", "Avocado", "Abroteus"]

当然,这是一个简单的示例,并且很可能是一个非常适合过滤器(filter)的用例。尽管如此,我们还是把5行混乱的代码变成了….0行?在第一个示例中,我们已经使用了一行代码来声明数组。

这里的乐趣并没有到此为止:我们用过滤器来做例子,但还有更多像map, reduce, sort和flatten这样的用法。它们为我们编写有创意,优雅,最重要的是易于理解的代码提供了巨大的空间! F3ya2yQ.jpg!web

你怎么认为?也许我的例子有失偏颇,也许我完全错了。请在评论中告诉我-我感谢任何和所有的反馈!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK