chore(i8n,learn): processed translations

This commit is contained in:
Crowdin Bot
2021-02-06 04:42:36 +00:00
committed by Mrugesh Mohapatra
parent 15047f2d90
commit e5c44a3ae5
3274 changed files with 172122 additions and 14164 deletions

View File

@ -1,6 +1,6 @@
---
id: 587d7da9367417b2b2512b67
title: 使用 concat 而不是 push 将元素添加到数组的末尾
title: Add Elements to the End of an Array Using concat Instead of push
challengeType: 1
forumTopicId: 301226
dashedName: add-elements-to-the-end-of-an-array-using-concat-instead-of-push
@ -8,9 +8,9 @@ dashedName: add-elements-to-the-end-of-an-array-using-concat-instead-of-push
# --description--
函数式编程就是创建和使用具有不变性的函数。
Functional programming is all about creating and using non-mutating functions.
上一个挑战介绍了`concat`方法,这是一种在不改变原始数组的前提下,将数组组合成新数组的方法。将`concat`方法与`push`方法做比较,`Push`将元素添加到调用它的数组的末尾,这样会改变该数组。举个例子:
The last challenge introduced the `concat` method as a way to combine arrays into a new one without mutating the original arrays. Compare `concat` to the `push` method. `Push` adds an item to the end of the same array it is called on, which mutates that array. Here's an example:
```js
var arr = [1, 2, 3];
@ -19,39 +19,39 @@ arr.push([4, 5, 6]);
// Not the functional programming way
```
`Concat`方法可以将新项目添加到数组末尾,而不产生任何变化。
`Concat` offers a way to add new items to the end of an array without any mutating side effects.
# --instructions--
修改`nonMutatingPush`函数,用`concat`替代`push``newItem`添加到`original`末尾,该函数应返回一个数组。
Change the `nonMutatingPush` function so it uses `concat` to add `newItem` to the end of `original` instead of `push`. The function should return an array.
# --hints--
应该使用`concat`方法。
Your code should use the `concat` method.
```js
assert(code.match(/\.concat/g));
```
不能使用`push`方法。
Your code should not use the `push` method.
```js
assert(!code.match(/\.push/g));
assert(!code.match(/\.?[\s\S]*?push/g));
```
不能改变`first`数组。
The `first` array should not change.
```js
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
```
不能改变`second`数组。
The `second` array should not change.
```js
assert(JSON.stringify(second) === JSON.stringify([4, 5]));
```
`nonMutatingPush([1, 2, 3], [4, 5])`应返回`[1, 2, 3, 4, 5]`
`nonMutatingPush([1, 2, 3], [4, 5])` should return `[1, 2, 3, 4, 5]`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7dab367417b2b2512b6d
title: 应用函数式编程将字符串转换为URL片段
title: Apply Functional Programming to Convert Strings to URL Slugs
challengeType: 1
forumTopicId: 301227
dashedName: apply-functional-programming-to-convert-strings-to-url-slugs
@ -8,51 +8,45 @@ dashedName: apply-functional-programming-to-convert-strings-to-url-slugs
# --description--
最后几个挑战中涵盖了许多符合函数式编程原则并在处理数组和字符串中非常有用的方法。我们还学习了强大的、可以将问题简化为更简单形式的`reduce`方法,从计算平均值到排序,任何数组操作都可以用它来实现。回想一下,`map``filter`方法都是`reduce`的特殊实现。
The last several challenges covered a number of useful array and string methods that follow functional programming principles. We've also learned about `reduce`, which is a powerful method used to reduce problems to simpler forms. From computing averages to sorting, any array operation can be achieved by applying it. Recall that `map` and `filter` are special cases of `reduce`.
让我们把学到的知识结合起来解决一个实际问题。
Let's combine what we've learned to solve a practical problem.
许多内容管理站点CMS为了让添加书签更简单会将帖子的标题添加到 URL 上。举个例子,如果你写了一篇标题为 "Stop Using Reduce" 的帖子URL很可能会包含标题字符串的某种形式 (如:".../stop-using-reduce"),你可能已经在 freeCodeCamp 网站上注意到了这一点。
Many content management sites (CMS) have the titles of a post added to part of the URL for simple bookmarking purposes. For example, if you write a Medium post titled "Stop Using Reduce", it's likely the URL would have some form of the title string in it (".../stop-using-reduce"). You may have already noticed this on the freeCodeCamp site.
# --instructions--
填写`urlSlug`函数,将字符串`title`转换成带有连字符号的 URL。您可以使用本节中介绍的任何方法但不要用`replace`方法。以下是本次挑战的要求:
Fill in the `urlSlug` function so it converts a string `title` and returns the hyphenated version for the URL. You can use any of the methods covered in this section, and don't use `replace`. Here are the requirements:
输入包含空格和标题大小写单词的字符串
The input is a string with spaces and title-cased words
输出字符串,单词之间的空格用连字符(`-`)替换
The output is a string with the spaces between words replaced by a hyphen (`-`)
输出应该是小写字母
The output should be all lower-cased letters
输出不应有任何空格
The output should not have any spaces
# --hints--
`globalTitle`变量应保持不变。
Your code should not use the `replace` method for this challenge.
```js
assert(globalTitle === 'Winter Is Coming');
assert(!code.match(/\.?[\s\S]*?replace/g));
```
在此挑战中不能使用`replace`方法。
```js
assert(!code.match(/\.replace/g));
```
`urlSlug('Winter Is Coming')`应返回`'winter-is-coming'`
`urlSlug("Winter Is Coming")` should return `"winter-is-coming"`.
```js
assert(urlSlug('Winter Is Coming') === 'winter-is-coming');
```
`urlSlug(' Winter Is  Coming')`应返回`'winter-is-coming'`
`urlSlug(" Winter Is Coming")` should return `"winter-is-coming"`.
```js
assert(urlSlug(' Winter Is Coming') === 'winter-is-coming');
```
`urlSlug('A Mind Needs Books Like A Sword Needs A Whetstone')`应返回`'a-mind-needs-books-like-a-sword-needs-a-whetstone'`
`urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")` should return `"a-mind-needs-books-like-a-sword-needs-a-whetstone"`.
```js
assert(
@ -61,7 +55,7 @@ assert(
);
```
`urlSlug('Hold The Door')`应返回`'hold-the-door'`
`urlSlug("Hold The Door")` should return `"hold-the-door"`.
```js
assert(urlSlug('Hold The Door') === 'hold-the-door');

View File

@ -1,6 +1,6 @@
---
id: 587d7b8e367417b2b2512b5e
title: 使用函数式编程避免变化和副作用
title: Avoid Mutations and Side Effects Using Functional Programming
challengeType: 1
forumTopicId: 301228
dashedName: avoid-mutations-and-side-effects-using-functional-programming
@ -8,34 +8,47 @@ dashedName: avoid-mutations-and-side-effects-using-functional-programming
# --description--
如果你还没想通,上一个挑战的问题出在`tabClose()`函数里的`splice`。不幸的是,`splice`修改了调用它的原始数组,所以第二次调用它时是基于修改后的数组,才给出了意料之外的结果。
If you haven't already figured it out, the issue in the previous challenge was with the `splice` call in the `tabClose()` function. Unfortunately, `splice` changes the original array it is called on, so the second call to it used a modified array, and gave unexpected results.
这是一个小例子,还有更广义的定义——在变量,数组或对象上调用一个函数,这个函数会改变对象中的变量或其他东西。
This is a small example of a much larger pattern - you call a function on a variable, array, or an object, and the function changes the variable or something in the object.
函数式编程的核心原则之一是不改变任何东西。变化会导致错误。如果一个函数不改变传入的参数、全局变量等数据,那么它造成问题的可能性就会小很多。
One of the core principles of functional programming is to not change things. Changes lead to bugs. It's easier to prevent bugs knowing that your functions don't change anything, including the function arguments or any global variable.
前面的例子没有任何复杂的操作,但是`splice`方法改变了原始数组,导致 bug 产生。
The previous example didn't have any complicated operations but the `splice` method changed the original array, and resulted in a bug.
回想一下,在函数式编程中,改变或变更叫做`mutation`,这种改变的结果叫做“副作用”(`side effect`)。理想情况下,函数应该是不会产生任何副作用的`纯函数`
Recall that in functional programming, changing or altering things is called <dfn>mutation</dfn>, and the outcome is called a <dfn>side effect</dfn>. A function, ideally, should be a <dfn>pure function</dfn>, meaning that it does not cause any side effects.
让我们尝试掌握这个原则:不要改变代码中的任何变量或对象。
Let's try to master this discipline and not alter any variable or object in our code.
# --instructions--
填写`incrementer`函数的代码,使其返回全局变量`fixedValue`的值增加 1。
Fill in the code for the function `incrementer` so it returns the value of the global variable `fixedValue` increased by one.
# --hints--
`incrementer`函数不能改变`fixedValue`的值。
Your function `incrementer` should not change the value of `fixedValue` (which is `4`).
```js
incrementer();
assert(fixedValue === 4);
```
`incrementer`函数应返回比`fixedValue`变量更大的值。
Your `incrementer` function should return a value that is one larger than the `fixedValue` value.
```js
assert(newValue === 5);
const __newValue = incrementer();
assert(__newValue === 5);
```
Your `incrementer` function should return a value based on the global `fixedValue` variable value.
```js
(function () {
fixedValue = 10;
const newValue = incrementer();
assert(fixedValue === 10 && newValue === 11);
fixedValue = 4;
})();
```
# --seed--

View File

@ -1,6 +1,6 @@
---
id: 587d7daa367417b2b2512b6c
title: 使用 join 方法将数组组合成字符串
title: Combine an Array into a String Using the join Method
challengeType: 1
forumTopicId: 18221
dashedName: combine-an-array-into-a-string-using-the-join-method
@ -8,9 +8,9 @@ dashedName: combine-an-array-into-a-string-using-the-join-method
# --description--
`join`方法用来把数组中的所有元素放入一个字符串,并通过指定的分隔符参数进行分隔。
The `join` method is used to join the elements of an array together to create a string. It takes an argument for the delimiter that is used to separate the array elements in the string.
举个例子:
Here's an example:
```js
var arr = ["Hello", "World"];
@ -20,35 +20,35 @@ var str = arr.join(" ");
# --instructions--
在函数`sentensify`内用`join`方法(及其他方法)用字符串`str`中的单词造句,这个函数应返回一个字符串。举个例子,"I-like-Star-Wars" 会被转换成 "I like Star Wars"。在此挑战中请勿使用`replace`方法。
Use the `join` method (among others) inside the `sentensify` function to make a sentence from the words in the string `str`. The function should return a string. For example, "I-like-Star-Wars" would be converted to "I like Star Wars". For this challenge, do not use the `replace` method.
# --hints--
应使用`join`方法。
Your code should use the `join` method.
```js
assert(code.match(/\.join/g));
```
不能使用`replace`方法。
Your code should not use the `replace` method.
```js
assert(!code.match(/\.replace/g));
assert(!code.match(/\.?[\s\S]*?replace/g));
```
`sentensify('May-the-force-be-with-you')`应返回一个字符串
`sentensify("May-the-force-be-with-you")` should return a string.
```js
assert(typeof sentensify('May-the-force-be-with-you') === 'string');
```
`sentensify('May-the-force-be-with-you')`应返回`'May the force be with you'`
`sentensify("May-the-force-be-with-you")` should return `"May the force be with you"`.
```js
assert(sentensify('May-the-force-be-with-you') === 'May the force be with you');
```
`sentensify('The.force.is.strong.with.this.one')`应返回`'The force is strong with this one'`
`sentensify("The.force.is.strong.with.this.one")` should return `"The force is strong with this one"`.
```js
assert(
@ -57,7 +57,7 @@ assert(
);
```
`sentensify('There,has,been,an,awakening')`应返回`'There has been an awakening'`
`sentensify("There,has,been,an,awakening")` should return `"There has been an awakening"`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7da9367417b2b2512b66
title: 使用 concat 方法组合两个数组
title: Combine Two Arrays Using the concat Method
challengeType: 1
forumTopicId: 301229
dashedName: combine-two-arrays-using-the-concat-method
@ -8,38 +8,38 @@ dashedName: combine-two-arrays-using-the-concat-method
# --description--
`Concatenation`意思是将元素连接到尾部。同理JavaScript 为字符串和数组提供了`concat`方法。对数组来说,在一个数组上调用`concat`方法,然后提供另一个数组作为参数添加到第一个数组末尾,返回一个新数组,不会改变任何一个原始数组。举个例子:
<dfn>Concatenation</dfn> means to join items end to end. JavaScript offers the `concat` method for both strings and arrays that work in the same way. For arrays, the method is called on one, then another array is provided as the argument to `concat`, which is added to the end of the first array. It returns a new array and does not mutate either of the original arrays. Here's an example:
```js
[1, 2, 3].concat([4, 5, 6]);
// 返回新数组 [1, 2, 3, 4, 5, 6]
// Returns a new array [1, 2, 3, 4, 5, 6]
```
# --instructions--
`nonMutatingConcat`函数里使用`concat`,将`attach`拼接到`original`尾部,返回拼接后的数组。
Use the `concat` method in the `nonMutatingConcat` function to concatenate `attach` to the end of `original`. The function should return the concatenated array.
# --hints--
应该使用`concat`方法。
Your code should use the `concat` method.
```js
assert(code.match(/\.concat/g));
```
不能改变`first`数组。
The `first` array should not change.
```js
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
```
不能改变`second`数组。
The `second` array should not change.
```js
assert(JSON.stringify(second) === JSON.stringify([4, 5]));
```
`nonMutatingConcat([1, 2, 3], [4, 5])`应返回`[1, 2, 3, 4, 5]`
`nonMutatingConcat([1, 2, 3], [4, 5])` should return `[1, 2, 3, 4, 5]`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b8f367417b2b2512b62
title: 在原型上实现 map 方法
title: Implement map on a Prototype
challengeType: 1
forumTopicId: 301230
dashedName: implement-map-on-a-prototype
@ -8,30 +8,28 @@ dashedName: implement-map-on-a-prototype
# --description--
我们之前用`map`方法(即`Array.prototype.map()`)返回一个与调用它的数组长度相同的数组。只要它的回调函数不改变原始数组,它就不会改变原始数组。
As you have seen from applying `Array.prototype.map()`, or simply `map()` earlier, the `map` method returns an array of the same length as the one it was called on. It also doesn't alter the original array, as long as its callback function doesn't.
换句话说,`map`是一个纯函数,它的输出仅取决于输入的数组和作为参数传入的回调函数。
In other words, `map` is a pure function, and its output depends solely on its inputs. Plus, it takes another function as its argument.
为了加深对`map`方法的理解,现在我们来用`for``Array.prototype.forEach()`自己实现一下这个方法。
注意:纯函数可以改变其作用域内定义的局部变量,但我们最好不要这样做。
You might learn a lot about the `map` method if you implement your own version of it. It is recommended you use a `for` loop or `Array.prototype.forEach()`.
# --instructions--
写一个和`Array.prototype.map()`一样的`Array.prototype.myMap()`。你可以用`for`循环或者`forEach`方法。
Write your own `Array.prototype.myMap()`, which should behave exactly like `Array.prototype.map()`. You should not use the built-in `map` method. The `Array` instance can be accessed in the `myMap` method using `this`.
# --hints--
`new_s`应等于`[46, 130, 196, 10]`
`new_s` should equal `[46, 130, 196, 10]`.
```js
assert(JSON.stringify(new_s) === JSON.stringify([46, 130, 196, 10]));
```
不能使用`map`方法。
Your code should not use the `map` method.
```js
assert(!code.match(/\.map/g));
assert(!code.match(/\.?[\s\S]*?map/g));
```
# --seed--

View File

@ -1,6 +1,6 @@
---
id: 587d7b8f367417b2b2512b64
title: 在原型上实现 filter 方法
title: Implement the filter Method on a Prototype
challengeType: 1
forumTopicId: 301231
dashedName: implement-the-filter-method-on-a-prototype
@ -8,26 +8,24 @@ dashedName: implement-the-filter-method-on-a-prototype
# --description--
为了加深对`filter`的理解,现在我们来自己实现一下`Array.prototype.filter()`方法。可以用`for`循环或`Array.prototype.forEach()`
请注意:纯函数可以改变其作用域内定义的局部变量,但我们最好不要这样做。
You might learn a lot about the `filter` method if you implement your own version of it. It is recommended you use a `for` loop or `Array.prototype.forEach()`.
# --instructions--
编写一个和`Array.prototype.filter()`功能一样的`Array.prototype.myFilter()`方法。你可以用`for`循环或`Array.prototype.forEach()`方法。
Write your own `Array.prototype.myFilter()`, which should behave exactly like `Array.prototype.filter()`. You should not use the built-in `filter` method. The `Array` instance can be accessed in the `myFilter` method using `this`.
# --hints--
`new_s`应等于`[23, 65, 5]`
`new_s` should equal `[23, 65, 5]`.
```js
assert(JSON.stringify(new_s) === JSON.stringify([23, 65, 5]));
```
不能使用`filter`方法。
Your code should not use the `filter` method.
```js
assert(!code.match(/\.filter/g));
assert(!code.match(/\.?[\s\S]*?filter/g));
```
# --seed--

View File

@ -1,6 +1,6 @@
---
id: 587d7dab367417b2b2512b70
title: 函数柯里化
title: Introduction to Currying and Partial Application
challengeType: 1
forumTopicId: 301232
dashedName: introduction-to-currying-and-partial-application
@ -8,11 +8,11 @@ dashedName: introduction-to-currying-and-partial-application
# --description--
`arity`是函数所需的形参的数量。函数`柯里化`意思是把接受多个`arity`的函数变换成接受单一`arity`的函数。
The <dfn>arity</dfn> of a function is the number of arguments it requires. <dfn>Currying</dfn> a function means to convert a function of N arity into N functions of arity 1.
换句话说,就是重构函数让它接收一个参数,然后返回接收下一个参数的函数,依此类推。
In other words, it restructures a function so it takes one argument, then returns another function that takes the next argument, and so on.
举个例子:
Here's an example:
```js
//Un-curried function
@ -20,7 +20,7 @@ function unCurried(x, y) {
return x + y;
}
//柯里化函数
//Curried function
function curried(x) {
return function(y) {
return x + y;
@ -29,10 +29,10 @@ function curried(x) {
//Alternative using ES6
const curried = x => y => x + y
curried(1)(2) // 返回 3
curried(1)(2) // Returns 3
```
柯里化在不能一次为函数提供所有参数情况下很有用。因为它可以将每个函数的调用保存到一个变量中,该变量将保存返回的函数引用,该引用在下一个参数可用时接受该参数。下面是使用`柯里化`函数的例子:
This is useful in your program if you can't supply all the arguments to a function at one time. You can save each function call into a variable, which will hold the returned function reference that takes the next argument when it's available. Here's an example using the curried function in the example above:
```js
// Call a curried function in parts:
@ -40,7 +40,7 @@ var funcForY = curried(1);
console.log(funcForY(2)); // Prints 3
```
类似地,`局部应用`的意思是一次对一个函数应用几个参数,然后返回另一个应用更多参数的函数。 举个例子:
Similarly, <dfn>partial application</dfn> can be described as applying a few arguments to a function at a time and returning another function that is applied to more arguments. Here's an example:
```js
//Impartial function
@ -53,29 +53,29 @@ partialFn(10); // Returns 13
# --instructions--
填写`add`函数主体部分,用柯里化添加参数`x``y``z`.
Fill in the body of the `add` function so it uses currying to add parameters `x`, `y`, and `z`.
# --hints--
`add(10)(20)(30)`应返回`60`
`add(10)(20)(30)` should return `60`.
```js
assert(add(10)(20)(30) === 60);
```
`add(1)(2)(3)`应返回`6`
`add(1)(2)(3)` should return `6`.
```js
assert(add(1)(2)(3) === 6);
```
`add(11)(22)(33)`应返回`66`
`add(11)(22)(33)` should return `66`.
```js
assert(add(11)(22)(33) === 66);
```
应返回`x + y + z`的最终结果。
Your code should include a final statement that returns `x + y + z`.
```js
assert(code.match(/[xyz]\s*?\+\s*?[xyz]\s*?\+\s*?[xyz]/g));

View File

@ -1,6 +1,6 @@
---
id: 587d7b8d367417b2b2512b5b
title: 学习函数式编程
title: Learn About Functional Programming
challengeType: 1
forumTopicId: 301233
dashedName: learn-about-functional-programming
@ -8,33 +8,33 @@ dashedName: learn-about-functional-programming
# --description--
函数式编程是一种方案简单、功能独立、对作用域外没有任何副作用的编程范式。
Functional programming is a style of programming where solutions are simple, isolated functions, without any side effects outside of the function scope.
`INPUT -> PROCESS -> OUTPUT`
函数式编程:
Functional programming is about:
1)功能独立——不依赖于程序的状态(比如可能发生变化的全局变量);
1) Isolated functions - there is no dependence on the state of the program, which includes global variables that are subject to change
2)纯函数——同一个输入永远能得到同一个输出;
2) Pure functions - the same input always gives the same output
3)有限的副作用——可以严格地限制函数外部对状态的更改。
3) Functions with limited side effects - any changes, or mutations, to the state of the program outside the function are carefully controlled
# --instructions--
freeCodeCamp 成员在 love tea 的故事。
The members of freeCodeCamp happen to love tea.
在代码编辑器中,已经为你定义好了`prepareTea``getTea`函数。调用`getTea`函数为团队准备 40 杯茶,并将它们存储在`tea4TeamFCC`变量里。
In the code editor, the `prepareTea` and `getTea` functions are already defined for you. Call the `getTea` function to get 40 cups of tea for the team, and store them in the `tea4TeamFCC` variable.
# --hints--
`tea4TeamFCC`变量里应有 40 杯为团队准备的茶。
The `tea4TeamFCC` variable should hold 40 cups of tea for the team.
```js
assert(tea4TeamFCC.length === 40);
```
`tea4TeamFCC`变量里应有 greenTea
The `tea4TeamFCC` variable should hold cups of green tea.
```js
assert(tea4TeamFCC[0] === 'greenTea');
@ -75,7 +75,7 @@ const prepareTea = () => 'greenTea';
const getTea = (numOfCups) => {
const teaCups = [];
for(let cups = 1; cups <= numOfCups; cups += 1) {
const teaCup = prepareTea();
teaCups.push(teaCup);

View File

@ -1,6 +1,6 @@
---
id: 587d7b8e367417b2b2512b5f
title: 传递参数以避免函数中的外部依赖
title: Pass Arguments to Avoid External Dependence in a Function
challengeType: 1
forumTopicId: 301234
dashedName: pass-arguments-to-avoid-external-dependence-in-a-function
@ -8,42 +8,43 @@ dashedName: pass-arguments-to-avoid-external-dependence-in-a-function
# --description--
上一个挑战是更接近函数式编程原则的挑战,但是仍然缺少一些东西。
The last challenge was a step closer to functional programming principles, but there is still something missing.
虽然我们没有改变全局变量值,但在没有全局变量`fixedValue`情况下,`incrementer`函数将不起作用。
We didn't alter the global variable value, but the function `incrementer` would not work without the global variable `fixedValue` being there.
函数式编程的另一个原则是:总是显式声明依赖关系。如果函数依赖于一个变量或对象,那么将该变量或对象作为参数直接传递到函数中。
Another principle of functional programming is to always declare your dependencies explicitly. This means if a function depends on a variable or object being present, then pass that variable or object directly into the function as an argument.
这样做会有很多好处,其中一点是让函数更容易测试,因为你确切地知道参数是什么,并且这个参数也不依赖于程序中的任何其他内容。
There are several good consequences from this principle. The function is easier to test, you know exactly what input it takes, and it won't depend on anything else in your program.
其次,这样做可以让你更加自信地更改,删除或添加新代码。因为你很清楚哪些是可以改的,哪些是不可以改的,这样你就知道哪里可能会有潜在的陷阱。
This can give you more confidence when you alter, remove, or add new code. You would know what you can or cannot change and you can see where the potential traps are.
最后,无论代码的哪一部分执行它,函数总是会为同一组输入生成相同的输出。
Finally, the function would always produce the same output for the same set of inputs, no matter what part of the code executes it.
# --instructions--
更新`incrementer`函数,明确声明其依赖项。
Let's update the `incrementer` function to clearly declare its dependencies.
编写`incrementer`函数,获取它的参数,然后将值增加 1。
Write the `incrementer` function so it takes an argument, and then returns a result after increasing the value by one.
# --hints--
`incrementer`函数不能修改`fixedValue`的值。
Your function `incrementer` should not change the value of `fixedValue` (which is `4`).
```js
assert(fixedValue === 4);
```
`incrementer`函数应该接收一个参数。
Your `incrementer` function should take an argument.
```js
assert(incrementer.length === 1);
```
`incrementer`函数应返回比`fixedValue`更大的值。
Your `incrementer` function should return a value that is one larger than the `fixedValue` value.
```js
assert(newValue === 5);
const __newValue = incrementer(fixedValue);
assert(__newValue === 5);
```
# --seed--
@ -75,5 +76,5 @@ function incrementer (fixedValue) {
// Only change code above this line
}
```

View File

@ -1,6 +1,6 @@
---
id: 587d7b8f367417b2b2512b60
title: 在函数中重构全局变量
title: Refactor Global Variables Out of Functions
challengeType: 1
forumTopicId: 301235
dashedName: refactor-global-variables-out-of-functions
@ -8,21 +8,23 @@ dashedName: refactor-global-variables-out-of-functions
# --description--
目前为止,我们已经看到了函数式编程的两个原则:
So far, we have seen two distinct principles for functional programming:
1) 不要更改变量或对象——创建新变量和对象,并在需要时从函数返回它们。
1) Don't alter a variable or object - create new variables and objects and return them if need be from a function. Hint: using something like `var newArr = arrVar`, where `arrVar` is an array will simply create a reference to the existing variable and not a copy. So changing a value in `newArr` would change the value in `arrVar`.
2) 声明函数参数——函数内的任何计算仅取决于参数,而不取决于任何全局对象或变量。
2) Declare function parameters - any computation inside a function depends only on the arguments passed to the function, and not on any global object or variable.
给数字增加 1 不够刺激,我们可以在处理数组或更复杂的对象时应用这些原则。
Adding one to a number is not very exciting, but we can apply these principles when working with arrays or more complex objects.
# --instructions--
重构代码,使全局数组`bookList`在函数内部不会被改变。`add`函数可以将指定的`bookName`增加到数组末尾。`remove`函数可以从数组中移除指定`bookName`。两个函数都返回数组,并且任何参数都应该添加到`bookName`前面。
Rewrite the code so the global array `bookList` is not changed inside either function. The `add` function should add the given `bookName` to the end of the array passed to it and return a new array (list). The `remove` function should remove the given `bookName` from the array passed to it.
**Note:** Both functions should return an array, and any new parameters should be added before the `bookName` parameter.
# --hints--
`bookList`不应该改变,应等于`['The Hound of the Baskervilles', 'On The Electrodynamics of Moving Bodies', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae']`.
`bookList` should not change and still equal `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`.
```js
assert(
@ -36,7 +38,7 @@ assert(
);
```
`newBookList`应等于`['The Hound of the Baskervilles', 'On The Electrodynamics of Moving Bodies', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae', 'A Brief History of Time']`.
`newBookList` should equal `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]`.
```js
assert(
@ -51,7 +53,7 @@ assert(
);
```
`newerBookList`应等于`['The Hound of the Baskervilles', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae']`.
`newerBookList` should equal `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`.
```js
assert(
@ -64,7 +66,7 @@ assert(
);
```
`newestBookList`应等于`['The Hound of the Baskervilles', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae', 'A Brief History of Time']`.
`newestBookList` should equal `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]`.
```js
assert(
@ -91,7 +93,7 @@ function add (bookName) {
bookList.push(bookName);
return bookList;
// Change code above this line
}

View File

@ -1,6 +1,6 @@
---
id: 9d7123c8c441eeafaeb5bdef
title: 使用 slice 而不是 splice 从数组中移除元素
title: Remove Elements from an Array Using slice Instead of splice
challengeType: 1
forumTopicId: 301236
dashedName: remove-elements-from-an-array-using-slice-instead-of-splice
@ -8,7 +8,7 @@ dashedName: remove-elements-from-an-array-using-slice-instead-of-splice
# --description--
使用数组时经常遇到要删除一些元素并保留数组剩余部分的情况。为此JavaScript 提供了`splice`方法,它接收两个参数:从哪里开始删除项目的索引,和要删除的项目数。如果没有提供第二个参数,默认情况下是移除到结尾的元素。但`splice`方法会改变调用它的原始数组。举个例子:
A common pattern while working with arrays is when you want to remove items and keep the rest of the array. JavaScript offers the `splice` method for this, which takes arguments for the index of where to start removing items, then the number of items to remove. If the second argument is not provided, the default is to remove items through the end. However, the `splice` method mutates the original array it is called on. Here's an example:
```js
var cities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
@ -16,29 +16,29 @@ cities.splice(3, 1); // Returns "London" and deletes it from the cities array
// cities is now ["Chicago", "Delhi", "Islamabad", "Berlin"]
```
正如我们在上一次挑战中看到的那样,`slice`方法不会改变原始数组,而是返回一个可以保存到变量中的新数组。回想一下,`slice`方法接收两个参数,从开始索引开始选取到结束(不包括该元素),并在新数组中返回这些元素。使用`slice`方法替代`splice`有助于避免数组变化产生的副作用。
As we saw in the last challenge, the `slice` method does not mutate the original array, but returns a new one which can be saved into a variable. Recall that the `slice` method takes two arguments for the indices to begin and end the slice (the end is non-inclusive), and returns those items in a new array. Using the `slice` method instead of `splice` helps to avoid any array-mutating side effects.
# --instructions--
`slice`代替`splice`重写`nonMutatingSplice`函数。将`cities`数组长度限制为3并返回一个仅包含前 3 项的新数组。
Rewrite the function `nonMutatingSplice` by using `slice` instead of `splice`. It should limit the provided `cities` array to a length of 3, and return a new array with only the first three items.
不要改变提供给函数的原始数组。
Do not mutate the original array provided to the function.
# --hints--
应该使用`slice`方法。
Your code should use the `slice` method.
```js
assert(code.match(/\.slice/g));
```
不能使用`splice`方法。
Your code should not use the `splice` method.
```js
assert(!code.match(/\.splice/g));
assert(!code.match(/\.?[\s\S]*?splice/g));
```
不能改变`inputCities`数组。
The `inputCities` array should not change.
```js
assert(
@ -47,7 +47,7 @@ assert(
);
```
`nonMutatingSplice(['Chicago', 'Delhi', 'Islamabad', 'London', 'Berlin'])`应返回`['Chicago', 'Delhi', 'Islamabad']`
`nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])` should return `["Chicago", "Delhi", "Islamabad"]`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7da9367417b2b2512b6a
title: 在不更改原始数组的前提下返回排序后的数组
title: Return a Sorted Array Without Changing the Original Array
challengeType: 1
forumTopicId: 301237
dashedName: return-a-sorted-array-without-changing-the-original-array
@ -8,27 +8,27 @@ dashedName: return-a-sorted-array-without-changing-the-original-array
# --description--
`sort`方法会产生改变原始数组中元素顺序的副作用。换句话说,它会改变数组的位置。避免这种情况的一种方法是先将空数组连接到正在排序的数组上(记住`concat`返回一个新数组),再用`sort`方法。
A side effect of the `sort` method is that it changes the order of the elements in the original array. In other words, it mutates the array in place. One way to avoid this is to first concatenate an empty array to the one being sorted (remember that `slice` and `concat` return a new array), then run the `sort` method.
# --instructions--
`nonMutatingSort`函数中使用`sort`方法对数组中的元素按升序进行排列。函数不能改变`globalArray`变量,应返回一个新数组。
Use the `sort` method in the `nonMutatingSort` function to sort the elements of an array in ascending order. The function should return a new array, and not mutate the `globalArray` variable.
# --hints--
应该使用`sort`方法。
Your code should use the `sort` method.
```js
assert(nonMutatingSort.toString().match(/\.sort/g));
```
应该使用`concat`方法。
The `globalArray` variable should not change.
```js
assert(JSON.stringify(globalArray) === JSON.stringify([5, 6, 3, 2, 9]));
```
`globalArray`variable 应保持不变。
`nonMutatingSort(globalArray)` should return `[2, 3, 5, 6, 9]`.
```js
assert(
@ -37,12 +37,18 @@ assert(
);
```
`nonMutatingSort(globalArray)`应返回`[2, 3, 5, 6, 9]`
`nonMutatingSort(globalArray)` should not be hard coded.
```js
assert(!nonMutatingSort.toString().match(/[23569]/g));
```
The function should return a new array, not the array passed to it.
```js
assert(nonMutatingSort(globalArray) !== globalArray);
```
# --seed--
## --seed-contents--

View File

@ -1,6 +1,6 @@
---
id: 587d7b90367417b2b2512b65
title: 使用 slice 方法返回数组的一部分
title: Return Part of an Array Using the slice Method
challengeType: 1
forumTopicId: 301239
dashedName: return-part-of-an-array-using-the-slice-method
@ -8,9 +8,9 @@ dashedName: return-part-of-an-array-using-the-slice-method
# --description--
`slice`方法可以从已有数组中返回指定元素。它接受两个参数,第一个规定从何处开始选取,第二个规定从何处结束选取(不包括该元素)。如果没有传参,则默认为从数组的开头开始到结尾结束,这是复制整个数组的简单方式。`slice`返回一个新数组,不会修改原始数组。
The `slice` method returns a copy of certain elements of an array. It can take two arguments, the first gives the index of where to begin the slice, the second is the index for where to end the slice (and it's non-inclusive). If the arguments are not provided, the default is to start at the beginning of the array through the end, which is an easy way to make a copy of the entire array. The `slice` method does not mutate the original array, but returns a new one.
举个例子:
Here's an example:
```js
var arr = ["Cat", "Dog", "Tiger", "Zebra"];
@ -20,17 +20,17 @@ var newArray = arr.slice(1, 3);
# --instructions--
`sliceArray`函数中使用`slice`方法,给出`beginSlice``endSlice`索引,返回`anim`数组的一部分,这个函数应返回一个数组。
Use the `slice` method in the `sliceArray` function to return part of the `anim` array given the provided `beginSlice` and `endSlice` indices. The function should return an array.
# --hints--
你的代码中应使用`slice`方法。
Your code should use the `slice` method.
```js
assert(code.match(/\.slice/g));
```
不能改变`inputAnim`变量。
The `inputAnim` variable should not change.
```js
assert(
@ -39,7 +39,7 @@ assert(
);
```
`sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 1, 3)`应返回`['Dog', 'Tiger']`
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3)` should return `["Dog", "Tiger"]`.
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
`sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 0, 1)`应返回`['Cat']`
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1)` should return `["Cat"]`.
```js
assert(
@ -57,7 +57,7 @@ assert(
);
```
`sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 1, 4)`应返回`['Dog', 'Tiger', 'Zebra']`
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4)` should return `["Dog", "Tiger", "Zebra"]`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7da9367417b2b2512b69
title: 使用 sort 方法按字母顺序给数组排序
title: Sort an Array Alphabetically using the sort Method
challengeType: 1
forumTopicId: 18303
dashedName: sort-an-array-alphabetically-using-the-sort-method
@ -8,9 +8,9 @@ dashedName: sort-an-array-alphabetically-using-the-sort-method
# --description--
`sort`方法可以根据回调函数对数组元素进行排序。
The `sort` method sorts the elements of an array according to the callback function.
举个例子:
For example:
```js
function ascendingOrder(arr) {
@ -30,21 +30,21 @@ reverseAlpha(['l', 'h', 'z', 'b', 's']);
// Returns ['z', 's', 'l', 'h', 'b']
```
JavaScript 的默认排序方法是 Unicode 值顺序排序,有时可能会得到意想不到的结果。所以,建议传入一个回调函数指定数组项目的排序方式,这个回调函数通常叫做 `compareFunction`,它根据 `compareFunction` 的返回值决定数组元素的排序方式: 如果两个元素 `a``b``compareFunction(a,b)` 返回一个比 0 小的值,那么 `a` 会在 `b` 的前面。 如果两个元素 `a` `b``compareFunction(a,b)` 返回一个比 0 大的值,那么 `b` 会在 `a` 的前面。 如果两个元素 `a` `b``compareFunction(a,b)` 返回等于 0 的值,那么 `a` `b` 的位置保持不变。
JavaScript's default sorting method is by string Unicode point value, which may return unexpected results. Therefore, it is encouraged to provide a callback function to specify how to sort the array items. When such a callback function, normally called `compareFunction`, is supplied, the array elements are sorted according to the return value of the `compareFunction`: If `compareFunction(a,b)` returns a value less than 0 for two elements `a` and `b`, then `a` will come before `b`. If `compareFunction(a,b)` returns a value greater than 0 for two elements `a` and `b`, then `b` will come before `a`. If `compareFunction(a,b)` returns a value equal to 0 for two elements `a` and `b`, then `a` and `b` will remain unchanged.
# --instructions--
`alphabeticalOrder`函数中使用`sort`方法对`arr`中的元素按照字母顺序排列。
Use the `sort` method in the `alphabeticalOrder` function to sort the elements of `arr` in alphabetical order.
# --hints--
应该使用`sort`方法。
Your code should use the `sort` method.
```js
assert(code.match(/\.sort/g));
```
`alphabeticalOrder(['a', 'd', 'c', 'a', 'z', 'g'])`应返回`['a', 'a', 'c', 'd', 'g', 'z']`
`alphabeticalOrder(["a", "d", "c", "a", "z", "g"])` should return `["a", "a", "c", "d", "g", "z"]`.
```js
assert(
@ -53,7 +53,7 @@ assert(
);
```
`alphabeticalOrder(['x', 'h', 'a', 'm', 'n', 'm'])`应返回`['a', 'h', 'm', 'm', 'n', 'x']`
`alphabeticalOrder(["x", "h", "a", "m", "n", "m"])` should return `["a", "h", "m", "m", "n", "x"]`.
```js
assert(
@ -62,7 +62,7 @@ assert(
);
```
`alphabeticalOrder(['a', 'a', 'a', 'a', 'x', 't'])`应返回`['a', 'a', 'a', 'a', 't', 'x']`
`alphabeticalOrder(["a", "a", "a", "a", "x", "t"])` should return `["a", "a", "a", "a", "t", "x"]`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7daa367417b2b2512b6b
title: 使用 split 方法将字符串拆分成数组
title: Split a String into an Array Using the split Method
challengeType: 1
forumTopicId: 18305
dashedName: split-a-string-into-an-array-using-the-split-method
@ -8,9 +8,9 @@ dashedName: split-a-string-into-an-array-using-the-split-method
# --description--
`split`方法用于把字符串分割成字符串数组,接收一个分隔符参数,分隔符可以是用于分解字符串或正则表达式的字符。举个例子,如果分隔符是空格,你会得到一个单词数组;如果分隔符是空字符串,你会得到一个由字符串中每个字符组成的数组。
The `split` method splits a string into an array of strings. It takes an argument for the delimiter, which can be a character to use to break up the string or a regular expression. For example, if the delimiter is a space, you get an array of words, and if the delimiter is an empty string, you get an array of each character in the string.
下面是两个用空格分隔一个字符串的例子,另一个是用数字的正则表达式分隔:
Here are two examples that split one string by spaces, then another by digits using a regular expression:
```js
var str = "Hello World";
@ -22,21 +22,21 @@ var byDigits = otherString.split(/\d/);
// Sets byDigits to ["How", "are", "you", "today"]
```
因为字符串是固定的,`split`方法可以更简单的操作它们。
Since strings are immutable, the `split` method makes it easier to work with them.
# --instructions--
`splitify`函数中用`split`方法将`str`分割成单词数组,这个方法应该返回一个数组。单词不一定都是用空格分隔,所以数组中不应包含标点符号。
Use the `split` method inside the `splitify` function to split `str` into an array of words. The function should return the array. Note that the words are not always separated by spaces, and the array should not contain punctuation.
# --hints--
应该使用`split`方法。
Your code should use the `split` method.
```js
assert(code.match(/\.split/g));
```
`splitify('Hello World,I-am code')`应返回`['Hello', 'World', 'I', 'am', 'code']`
`splitify("Hello World,I-am code")` should return `["Hello", "World", "I", "am", "code"]`.
```js
assert(
@ -45,7 +45,7 @@ assert(
);
```
`splitify('Earth-is-our home')`应返回`['Earth', 'is', 'our', 'home']`
`splitify("Earth-is-our home")` should return `["Earth", "is", "our", "home"]`.
```js
assert(
@ -54,7 +54,7 @@ assert(
);
```
`splitify('This.is.a-sentence')`应返回`['This', 'is', 'a', 'sentence']`
`splitify("This.is.a-sentence")` should return `["This", "is", "a", "sentence"]`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b8e367417b2b2512b5c
title: 了解函数式编程术语
title: Understand Functional Programming Terminology
challengeType: 1
forumTopicId: 301240
dashedName: understand-functional-programming-terminology
@ -8,47 +8,47 @@ dashedName: understand-functional-programming-terminology
# --description--
FCC 团队需求有变更,现在想要两种茶:绿茶(green tea)和红茶(black tea)。事实证明,用户需求变更是很常见的。
The FCC Team had a mood swing and now wants two types of tea: green tea and black tea. General Fact: Client mood swings are pretty common.
基于以上信息,我们需要重构上一节挑战中的`getTea`函数来处理多种茶的请求。我们可以修改`getTea`接受一个函数作为参数,使它能够修改茶的类型。这让`getTea`更灵活,也使需求变更时为程序员提供更多控制权。
With that information, we'll need to revisit the `getTea` function from last challenge to handle various tea requests. We can modify `getTea` to accept a function as a parameter to be able to change the type of tea it prepares. This makes `getTea` more flexible, and gives the programmer more control when client requests change.
首先,我们将介绍一些术语:
But first, let's cover some functional terminology:
`Callbacks`是被传递到另一个函数中调用的函数。你应该已经在其他函数中看过这个写法,例如在`filter`中,回调函数告诉 JavaScript 以什么规则过滤数组。
<dfn>Callbacks</dfn> are the functions that are slipped or passed into another function to decide the invocation of that function. You may have seen them passed to other methods, for example in `filter`, the callback function tells JavaScript the criteria for how to filter an array.
函数就像其他正常值一样,可以赋值给变量、传递给另一个函数,或从其它函数返回,这种函数叫做`头等`函数。在 JavaScript 中,所有函数都是`头等`函数。
Functions that can be assigned to a variable, passed into another function, or returned from another function just like any other normal value, are called <dfn>first class</dfn> functions. In JavaScript, all functions are first class functions.
将函数为参数或返回值的函数叫做`高阶`函数。
The functions that take a function as an argument, or return a function as a return value are called <dfn>higher order</dfn> functions.
当函数传递给另一个函数或从另一个函数返回时,那些传入或返回的函数可以叫做`lambda`
When the functions are passed in to another function or returned from another function, then those functions which gets passed in or returned can be called a <dfn>lambda</dfn>.
# --instructions--
准备 27 杯绿茶和 13 杯红茶,分别存入`tea4GreenTeamFCC``tea4BlackTeamFCC`变量。请注意,`getTea`函数已经变了,现在它接收一个函数作为第一个参数。
Prepare 27 cups of green tea and 13 cups of black tea and store them in `tea4GreenTeamFCC` and `tea4BlackTeamFCC` variables, respectively. Note that the `getTea` function has been modified so it now takes a function as the first argument.
注意:数据(茶的数量)作为最后一个参数。我们将在后面的课程中对此进行更多讨论。
Note: The data (the number of cups of tea) is supplied as the last argument. We'll discuss this more in later lessons.
# --hints--
`tea4GreenTeamFCC`变量应存有为团队准备的 27 杯茶。
The `tea4GreenTeamFCC` variable should hold 27 cups of green tea for the team.
```js
assert(tea4GreenTeamFCC.length === 27);
```
`tea4GreenTeamFCC`变量应存有绿茶。
The `tea4GreenTeamFCC` variable should hold cups of green tea.
```js
assert(tea4GreenTeamFCC[0] === 'greenTea');
```
`tea4BlackTeamFCC`变量应存有 13 杯红茶。
The `tea4BlackTeamFCC` variable should hold 13 cups of black tea.
```js
assert(tea4BlackTeamFCC.length === 13);
```
`tea4BlackTeamFCC`变量应存有红茶。
The `tea4BlackTeamFCC` variable should hold cups of black tea.
```js
assert(tea4BlackTeamFCC[0] === 'blackTea');

View File

@ -1,6 +1,6 @@
---
id: 587d7b8e367417b2b2512b5d
title: 了解使用命令式编程的危害
title: Understand the Hazards of Using Imperative Code
challengeType: 1
forumTopicId: 301241
dashedName: understand-the-hazards-of-using-imperative-code
@ -8,31 +8,31 @@ dashedName: understand-the-hazards-of-using-imperative-code
# --description--
函数式编程是一种好习惯,它能让代码管理更简单,不受隐藏 bug 影响。在我们开始函数式编程之前,为了更好的突显可能遇到的问题,我们先看看命令式编程。
Functional programming is a good habit. It keeps your code easy to manage, and saves you from sneaky bugs. But before we get there, let's look at an imperative approach to programming to highlight where you may have issues.
类似在英语(和许多其他语言)中,命令式时态用于给出命令,编程中的命令式是给计算机一组语句来执行任务。
In English (and many other languages), the imperative tense is used to give commands. Similarly, an imperative style in programming is one that gives the computer a set of statements to perform a task.
这些语句通常会改变程序的状态,例如更新全局变量,典型的例子就是写一个 `for` 循环,它给出了迭代数组索引的精确方向。
Often the statements change the state of the program, like updating global variables. A classic example is writing a `for` loop that gives exact directions to iterate over the indices of an array.
相反,函数式编程是声明式编程的一种形式,通过调用方法或函数来告诉计算机要做什么。
In contrast, functional programming is a form of declarative programming. You tell the computer what you want done by calling a method or function.
JavaScript 提供了许多处理常见任务的方法,所以你无需写出计算机应如何执行它们。例如,你可以用 `map` 函数替代上面提到的 `for` 循环来处理数组迭代。这有助于避免语义错误,如调试章节介绍的"Off By One Errors"。
JavaScript offers many predefined methods that handle common tasks so you don't need to write out how the computer should perform them. For example, instead of using the `for` loop mentioned above, you could call the `map` method which handles the details of iterating over an array. This helps to avoid semantic errors, like the "Off By One Errors" that were covered in the Debugging section.
考虑这样的场景:你正在浏览器中浏览网页,并想操作你打开的标签。下面我们来试试用面向对象的思路来描述这种情景。
Consider the scenario: you are browsing the web in your browser, and want to track the tabs you have opened. Let's try to model this using some simple object-oriented code.
窗口对象由选项卡组成,通常会打开多个窗口。窗口对象中每个打开网站的标题都保存在一个数组中。在对浏览器进行了如打开新标签、合并窗口、关闭标签之类的操作后,你需要输出所有打开的标签。关掉的标签将从数组中删除,新打开的标签(为简单起见)则添加到数组的末尾。
A Window object is made up of tabs, and you usually have more than one Window open. The titles of each open site in each Window object is held in an array. After working in the browser (opening new tabs, merging windows, and closing tabs), you want to print the tabs that are still open. Closed tabs are removed from the array and new tabs (for simplicity) get added to the end of it.
代码编辑器中显示了此功能的实现,其中包含 `tabOpen()``tabClose()`,和 `join()` 函数。tabs数组是窗口对象的一部分用于储存打开页面的名称。
The code editor shows an implementation of this functionality with functions for `tabOpen()`, `tabClose()`, and `join()`. The array `tabs` is part of the Window object that stores the name of the open pages.
# --instructions--
在编辑器中运行代码。它使用了有副作用的方法,导致输出错误。打开标签的最终列表应该是 `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']` 但输出会略有不同。
Examine the code in the editor. It's using a method that has side effects in the program, causing incorrect behaviour. The final list of open tabs, stored in `finalTabs.tabs`, should be `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']` but the list produced by the code is slightly different.
修改 `Window.prototype.tabClose` 使其删除正确的标签。
Change `Window.prototype.tabClose` so that it removes the correct tab.
# --hints--
`finalTabs.tabs` 应该是 `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']`
`finalTabs.tabs` should be `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']`
```js
assert.deepEqual(finalTabs.tabs, [

View File

@ -1,6 +1,6 @@
---
id: 587d7b88367417b2b2512b45
title: 使用高阶函数 mapfilter 或者 reduce 来解决复杂问题
title: 'Use Higher-Order Functions map, filter, or reduce to Solve a Complex Problem'
challengeType: 1
forumTopicId: 301311
dashedName: use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-problem
@ -8,42 +8,46 @@ dashedName: use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-p
# --description--
已经接触了高阶函数如 `map()` `filter()` `reduce()`的使用,是时候用它们来完成一些复杂的挑战了。
Now that you have worked through a few challenges using higher-order functions like `map()`, `filter()`, and `reduce()`, you now get to apply them to solve a more complex challenge.
# --instructions--
已经定义了一个函数 `squareList`。任意组合 `map()``filter()` `reduce()` 来完成函数,满足以下条件,当传入实数数组(如,`[-3, 4.8, 5, 3, -3.2]`)时,返回*仅*包含正整数的平方的新数组。
We have defined a function named `squareList`. You need to complete the code for the `squareList` function using any combination of `map()`, `filter()`, and `reduce()` so that it returns a new array containing only the square of *only* the positive integers (decimal numbers are not integers) when an array of real numbers is passed to it. An example of an array containing only real numbers is `[-3, 4.8, 5, 3, -3.2]`.
**注意:** 函数不应该包含任何形式的 `for` 或者 `while` 循环或者 `forEach()` 函数。
**Note:** Your function should not use any kind of `for` or `while` loops or the `forEach()` function.
# --hints--
`squareList` 应该是一个 `function`
`squareList` should be a `function`.
```js
assert.typeOf(squareList, 'function'),
'<code>squareList</code> should be a <code>function</code>';
```
不应该使用 for 或者 while 循环或者 forEach。
`for`, `while`, and `forEach` should not be used.
```js
assert(!removeJSComments(code).match(/for|while|forEach/g));
assert(!__helpers.removeJSComments(code).match(/for|while|forEach/g));
```
应该使用 `map``filter` 或者 `reduce`
`map`, `filter`, or `reduce` should be used.
```js
assert(removeJSComments(code).match(/\.(map|filter|reduce)\s*\(/g));
assert(
__helpers
.removeWhiteSpace(__helpers.removeJSComments(code))
.match(/\.(map|filter|reduce)\(/g)
);
```
函数应该返回 `array`
The function should return an `array`.
```js
assert(Array.isArray(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])));
```
`squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])` 应该返回 `[16, 1764, 36]`
`squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])` should return `[16, 1764, 36]`.
```js
assert.deepStrictEqual(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]), [
@ -53,7 +57,7 @@ assert.deepStrictEqual(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]), [
]);
```
`squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3])` 应该返回 `[9, 100, 49]`
`squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3])` should return `[9, 100, 49]`.
```js
assert.deepStrictEqual(squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3]), [

View File

@ -1,6 +1,6 @@
---
id: 587d7dab367417b2b2512b6e
title: 使用 every 方法检查数组中的每个元素是否符合条件
title: Use the every Method to Check that Every Element in an Array Meets a Criteria
challengeType: 1
forumTopicId: 301312
dashedName: use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria
@ -8,9 +8,9 @@ dashedName: use-the-every-method-to-check-that-every-element-in-an-array-meets-a
# --description--
`every`方法用于检测数组中*所有*元素是否都符合指定条件。如果所有元素满足条件,返回布尔值`true`,反之返回`false`
The `every` method works with arrays to check if *every* element passes a particular test. It returns a Boolean value - `true` if all values meet the criteria, `false` if not.
举个例子,下面的代码检测数组`numbers`的所有元素是否都小于 10
For example, the following code would check if every element in the `numbers` array is less than 10:
```js
var numbers = [1, 5, 8, 0, 10, 11];
@ -22,29 +22,29 @@ numbers.every(function(currentValue) {
# --instructions--
`checkPositive`函数中使用`every`方法检查`arr`中是否所有元素都是正数,函数应返回一个布尔值。
Use the `every` method inside the `checkPositive` function to check if every element in `arr` is positive. The function should return a Boolean value.
# --hints--
应使用`every`方法。
Your code should use the `every` method.
```js
assert(code.match(/\.every/g));
```
`checkPositive([1, 2, 3, -4, 5])`应返回`false`
`checkPositive([1, 2, 3, -4, 5])` should return `false`.
```js
assert.isFalse(checkPositive([1, 2, 3, -4, 5]));
```
`checkPositive([1, 2, 3, 4, 5])`应返回`true`
`checkPositive([1, 2, 3, 4, 5])` should return `true`.
```js
assert.isTrue(checkPositive([1, 2, 3, 4, 5]));
```
`checkPositive([1, -2, 3, -4, 5])`应返回`false`
`checkPositive([1, -2, 3, -4, 5])` should return `false`.
```js
assert.isFalse(checkPositive([1, -2, 3, -4, 5]));

View File

@ -1,6 +1,6 @@
---
id: 587d7b8f367417b2b2512b63
title: 使用 filter 方法从数组中提取数据
title: Use the filter Method to Extract Data from an Array
challengeType: 1
forumTopicId: 18179
dashedName: use-the-filter-method-to-extract-data-from-an-array
@ -8,13 +8,13 @@ dashedName: use-the-filter-method-to-extract-data-from-an-array
# --description--
另一个有用的数组方法是`filter()`(即`Array.prototype.filter()`)。`filter`方法会返回一个长度不大于原始数组的新数组。
Another useful array function is `Array.prototype.filter()`, or simply `filter()`.
`map`一样,`Filter`不会改变原始数组,它接收一个回调函数,将回调内的逻辑应用于数组的每个元素。新数组包含根据回调函数内条件返回 true 的元素。
`filter` calls a function on each element of an array and returns a new array containing only the elements for which that function returns `true`. In other words, it filters the array, based on the function passed to it. Like `map`, it does this without needing to modify the original array.
回调函数接收三个参数。第一个参数是当前正在被处理的元素,第二个参数是元素的索引,第三个参数是在其上调用 `filter` 方法的数组。
The callback function accepts three arguments. The first argument is the current element being processed. The second is the index of that element and the third is the array upon which the `filter` method was called.
看下在 `users` 上使用 `filter` 方法的例子,返回了一个新数组包含了 30 岁以下的用户。为了简化,例子里只使用了回调函数的第一个参数。
See below for an example using the `filter` method on the `users` array to return a new array containing only the users under the age of 30. For simplicity, the example only uses the first argument of the callback.
```js
const users = [
@ -29,11 +29,11 @@ console.log(usersUnder30); // [ { name: 'Amy', age: 20 }, { name: 'camperCat', a
# --instructions--
`watchList`是包含一些电影信息的对象。结合`filter``map`返回一个只包含`title``rating`属性的新数组,并且`imdbRating`值大于或等于 8.0。请注意,评级值在对象中保存为字符串,你可能需要将它转换成数字来执行运算。
The variable `watchList` holds an array of objects with information on several movies. Use a combination of `filter` and `map` on `watchList` to assign a new array of objects with only `title` and `rating` keys. The new array should only include objects where `imdbRating` is greater than or equal to 8.0. Note that the rating values are saved as strings in the object and you may need to convert them into numbers to perform mathematical operations on them.
# --hints--
`watchList`应保持不变。
The `watchList` variable should not change.
```js
assert(
@ -41,19 +41,19 @@ assert(
);
```
应使用`filter`方法。
Your code should use the `filter` method.
```js
assert(code.match(/\.filter/g));
```
不能使用`for`循环。
Your code should not use a `for` loop.
```js
assert(!code.match(/for\s*?\(.+?\)/g));
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
```
`filteredList`应等于`[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]`
`filteredList` should equal `[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]`.
```js
assert.deepEqual(filteredList, [

View File

@ -1,6 +1,6 @@
---
id: 587d7b8f367417b2b2512b61
title: 使用 map 方法从数组中提取数据
title: Use the map Method to Extract Data from an Array
challengeType: 1
forumTopicId: 18214
dashedName: use-the-map-method-to-extract-data-from-an-array
@ -8,19 +8,19 @@ dashedName: use-the-map-method-to-extract-data-from-an-array
# --description--
目前为止,我们已经学会了使用纯函数来避免程序中的副作用。此外,我们已经看到函数的值仅取决于其输入参数。
So far we have learned to use pure functions to avoid side effects in a program. Also, we have seen the value in having a function only depend on its input arguments.
这仅仅是个开始。顾名思义,函数式编程以函数理论为中心。
This is only the beginning. As its name suggests, functional programming is centered around a theory of functions.
能够将它们作为参数传递给其他函数,和从另一个函数返回一个函数是有意义的。函数在 JavaScript 中被视为`First Class Objects`,它们可以像任何其他对象一样使用。它们可以保存在变量中,存储在对象中,也可以作为函数参数传递。
It would make sense to be able to pass them as arguments to other functions, and return a function from another function. Functions are considered <dfn>first class objects</dfn> in JavaScript, which means they can be used like any other object. They can be saved in variables, stored in an object, or passed as function arguments.
让我们从一些简单的数组函数开始,这些函数是数组对象原型上的方法。在本练习中,我们来了解下数组的`map`方法(即`Array.prototype.map()`)。
Let's start with some simple array functions, which are methods on the array object prototype. In this exercise we are looking at `Array.prototype.map()`, or more simply `map`.
请记住,`map`方法是迭代数组中每一项的方式之一。在对每个元素应用回调函数后,它会创建一个新数组(不改变原来的数组)。
The `map` method iterates over each item in an array and returns a new array containing the results of calling the callback function on each element. It does this without mutating the original array.
当调用回调函数时,传入了三个参数。第一个参数是当前正在处理的数组项,第二个参数是当前数组项的索引值,第三个参数是在其上调用 `map` 方法的数组。
When the callback is used, it is passed three arguments. The first argument is the current element being processed. The second is the index of that element and the third is the array upon which the `map` method was called.
看下在 `users` 上使用 `map` 方法的例子,返回了一个新数组只包含了用户的名字。为了简化,例子里只使用了回调函数的第一个参数。
See below for an example using the `map` method on the `users` array to return a new array containing only the names of the users as elements. For simplicity, the example only uses the first argument of the callback.
```js
const users = [
@ -35,11 +35,11 @@ console.log(names); // [ 'John', 'Amy', 'camperCat' ]
# --instructions--
`watchList`数组保存了包含一些电影信息的对象。使用`map``watchList`中提取标题(`title`)和评分(`rating`),并将新数组保存在`rating`变量里。目前编辑器中的代码是使用`for`循环实现,使用`map`表达式替换循环功能。
The `watchList` array holds objects with information on several movies. Use `map` on `watchList` to assign a new array of objects with only `title` and `rating` keys to the `ratings` variable. The code in the editor currently uses a `for` loop to do this, so you should replace the loop functionality with your `map` expression.
# --hints--
`watchList`不能被改变
The `watchList` variable should not change.
```js
assert(
@ -47,31 +47,28 @@ assert(
);
```
你的代码不能使用`for`循环。
Your code should not use a `for` loop.
```js
assert(!removeJSComments(code).match(/for\s*?\(.*?\)/));
assert(!__helpers.removeJSComments(code).match(/for\s*?\([\s\S]*?\)/));
```
你的代码应使用`map`方法。
Your code should use the `map` method.
```js
assert(code.match(/\.map/g));
```
`rating`应等于`[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]`.
`ratings` should equal `[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]`.
```js
assert(
JSON.stringify(ratings) ===
JSON.stringify([
{ title: 'Inception', rating: '8.8' },
{ title: 'Interstellar', rating: '8.6' },
{ title: 'The Dark Knight', rating: '9.0' },
{ title: 'Batman Begins', rating: '8.3' },
{ title: 'Avatar', rating: '7.9' }
])
);
assert.deepEqual(ratings, [
{ title: 'Inception', rating: '8.8' },
{ title: 'Interstellar', rating: '8.6' },
{ title: 'The Dark Knight', rating: '9.0' },
{ title: 'Batman Begins', rating: '8.3' },
{ title: 'Avatar', rating: '7.9' }
]);
```
# --seed--

View File

@ -1,6 +1,6 @@
---
id: 587d7da9367417b2b2512b68
title: 使用 reduce 方法分析数据
title: Use the reduce Method to Analyze Data
challengeType: 1
forumTopicId: 301313
dashedName: use-the-reduce-method-to-analyze-data
@ -8,15 +8,15 @@ dashedName: use-the-reduce-method-to-analyze-data
# --description--
`reduce()`(即`Array.prototype.reduce()`),是 JavaScript 所有数组操作中最常用的方法。几乎可以用`reduce`方法解决所有数组处理问题。
`Array.prototype.reduce()`, or simply `reduce()`, is the most general of all array operations in JavaScript. You can solve almost any array processing problem using the `reduce` method.
`reduce`方法是处理数组更通用的方式,而且`filter``map`方法都可以当作是`reduce`的特殊实现。 `reduce`方法遍历数组中的每个项目并返回单个值(即字符串、数字、对象、数组)。 这是通过在每次迭代中调用一个回调函数来实现的。
The `reduce` method allows for more general forms of array processing, and it's possible to show that both `filter` and `map` can be derived as special applications of `reduce`. The `reduce` method iterates over each item in an array and returns a single value (i.e. string, number, object, array). This is achieved via a callback function that is called on each iteration.
回调函数接受四个参数。第一个参数称为叠加器,它是上一次迭代中回调函数的返回值,第二个参数是当前正在处理的数组元素,第三个参数是该参数的索引,第四个参数是在其上调用 `reduce` 方法的数组。
The callback function accepts four arguments. The first argument is known as the accumulator, which gets assigned the return value of the callback function from the previous iteration, the second is the current element being processed, the third is the index of that element and the fourth is the array upon which `reduce` is called.
除了回调函数,`reduce` 还有一个额外的参数做为叠加器的初始值。如果没有第二个参数,会跳过第一次迭代,第二次迭代给叠加器传入数组的第一个元素。
In addition to the callback function, `reduce` has an additional parameter which takes an initial value for the accumulator. If this second parameter is not used, then the first iteration is skipped and the second iteration gets passed the first element of the array as the accumulator.
见下面的例子,给 `users` 数组使用 `reduce` 方法,返回所有用户数组的和。为了简化,例子仅使用了回调函数的第一个参数和第二个参数。
See below for an example using `reduce` on the `users` array to return the sum of all the users' ages. For simplicity, the example only uses the first and second arguments.
```js
const users = [
@ -29,7 +29,7 @@ const sumOfAges = users.reduce((sum, user) => sum + user.age, 0);
console.log(sumOfAges); // 64
```
在另一个例子里,查看如何返回一个包含用户名称做为属性,其年龄做为值的对象。
In another example, see how an object can be returned containing the names of the users as properties with their ages as values.
```js
const users = [
@ -47,11 +47,11 @@ console.log(usersObj); // { John: 34, Amy: 20, camperCat: 10 }
# --instructions--
`watchList`变量中包含一组存有多部电影信息对象。使用`reduce`查找由**Christopher Nolan 导演**的电影的 IMDB 评级平均值。回想一下之前的挑战,如何`filter`数据,以及使用`map`来获取你想要的数据。你可能需要创建一些变量,但是请将最后的平均值保存到`averageRating`变量中。请注意,评级在对象中是字符串,需要将其转换为数字再用于数学运算。
The variable `watchList` holds an array of objects with information on several movies. Use `reduce` to find the average IMDB rating of the movies **directed by Christopher Nolan**. Recall from prior challenges how to `filter` data and `map` over it to pull what you need. You may need to create other variables, and return the average rating from `getRating` function. Note that the rating values are saved as strings in the object and need to be converted into numbers before they are used in any mathematical operations.
# --hints--
`watchList`应保持不变。
The `watchList` variable should not change.
```js
assert(
@ -59,25 +59,25 @@ assert(
);
```
应该使用`reduce`方法。
Your code should use the `reduce` method.
```js
assert(code.match(/\.reduce/g));
```
The`averageRating`应等于 8.675
The `getRating(watchList)` should equal 8.675.
```js
assert(getRating(watchList) === 8.675);
```
不能使用`for`循环。
Your code should not use a `for` loop.
```js
assert(!code.match(/for\s*?\(.*\)/g));
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
```
在修改 `watchList` 对象后应该返回正确的输出。
Your code should return correct output after modifying the `watchList` object.
```js
assert(getRating(watchList.filter((_, i) => i < 1 || i > 2)) === 8.55);

View File

@ -1,6 +1,6 @@
---
id: 587d7dab367417b2b2512b6f
title: 使用 some 方法检查数组中是否有元素是否符合条件
title: Use the some Method to Check that Any Elements in an Array Meet a Criteria
challengeType: 1
forumTopicId: 301314
dashedName: use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria
@ -8,9 +8,9 @@ dashedName: use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-cr
# --description--
`some`方法用于检测数组中*任何*元素是否满足指定条件。如果有一个元素满足条件,返回布尔值`true`,反之返回`false`
The `some` method works with arrays to check if *any* element passes a particular test. It returns a Boolean value - `true` if any of the values meet the criteria, `false` if not.
举个例子,下面的代码检测数组`numbers`中是否有元素小于10
For example, the following code would check if any element in the `numbers` array is less than 10:
```js
var numbers = [10, 50, 8, 220, 110, 11];
@ -22,29 +22,29 @@ numbers.some(function(currentValue) {
# --instructions--
`checkPositive`函数值中使用`some`检查`arr`中是否有元素为正数,函数应返回一个布尔值。
Use the `some` method inside the `checkPositive` function to check if any element in `arr` is positive. The function should return a Boolean value.
# --hints--
应该使用`some`method.
Your code should use the `some` method.
```js
assert(code.match(/\.some/g));
```
`checkPositive([1, 2, 3, -4, 5])`应返回`true`
`checkPositive([1, 2, 3, -4, 5])` should return `true`.
```js
assert(checkPositive([1, 2, 3, -4, 5]));
```
`checkPositive([1, 2, 3, 4, 5])`应返回`true`
`checkPositive([1, 2, 3, 4, 5])` should return `true`.
```js
assert(checkPositive([1, 2, 3, 4, 5]));
```
`checkPositive([-1, -2, -3, -4, -5])`应返回`false`
`checkPositive([-1, -2, -3, -4, -5])` should return `false`.
```js
assert(!checkPositive([-1, -2, -3, -4, -5]));