freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/avoid-mutations-and-side-effects-using-functional-programming.md
Oliver Eyton-Williams ee1e8abd87
feat(curriculum): restore seed + solution to Chinese (#40683)
* feat(tools): add seed/solution restore script

* chore(curriculum): remove empty sections' markers

* chore(curriculum): add seed + solution to Chinese

* chore: remove old formatter

* fix: update getChallenges

parse translated challenges separately, without reference to the source

* chore(curriculum): add dashedName to English

* chore(curriculum): add dashedName to Chinese

* refactor: remove unused challenge property 'name'

* fix: relax dashedName requirement

* fix: stray tag

Remove stray `pre` tag from challenge file.

Signed-off-by: nhcarrigan <nhcarrigan@gmail.com>

Co-authored-by: nhcarrigan <nhcarrigan@gmail.com>
2021-01-12 19:31:00 -07:00

1.8 KiB

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
587d7b8e367417b2b2512b5e 使用函数式编程避免变化和副作用 1 301228 avoid-mutations-and-side-effects-using-functional-programming

--description--

如果你还没想通,上一个挑战的问题出在tabClose()函数里的splice。不幸的是,splice修改了调用它的原始数组,所以第二次调用它时是基于修改后的数组,才给出了意料之外的结果。

这是一个小例子,还有更广义的定义——在变量,数组或对象上调用一个函数,这个函数会改变对象中的变量或其他东西。

函数式编程的核心原则之一是不改变任何东西。变化会导致错误。如果一个函数不改变传入的参数、全局变量等数据,那么它造成问题的可能性就会小很多。

前面的例子没有任何复杂的操作,但是splice方法改变了原始数组,导致 bug 产生。

回想一下,在函数式编程中,改变或变更叫做mutation,这种改变的结果叫做“副作用”(side effect)。理想情况下,函数应该是不会产生任何副作用的纯函数

让我们尝试掌握这个原则:不要改变代码中的任何变量或对象。

--instructions--

填写incrementer函数的代码,使其返回全局变量fixedValue的值增加 1。

--hints--

incrementer函数不能改变fixedValue的值。

assert(fixedValue === 4);

incrementer函数应返回比fixedValue变量更大的值。

assert(newValue === 5);

--seed--

--seed-contents--

// The global variable
var fixedValue = 4;

function incrementer () {
  // Only change code below this line


  // Only change code above this line
}

--solutions--

var fixedValue = 4

function incrementer() {
  return fixedValue + 1
}