chore(i8n,curriculum): processed translations (#41496)

Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
This commit is contained in:
camperbot
2021-03-15 14:01:16 -06:00
committed by GitHub
parent cd722a0e7f
commit dcadc249f4
44 changed files with 492 additions and 450 deletions

View File

@ -1,6 +1,6 @@
---
id: 587d7da9367417b2b2512b67
title: Add Elements to the End of an Array Using concat Instead of push
title: 使用 concat 而不是 push 将元素添加到数组的末尾
challengeType: 1
forumTopicId: 301226
dashedName: add-elements-to-the-end-of-an-array-using-concat-instead-of-push
@ -8,50 +8,50 @@ 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.
函数式编程就是创建和使用具有不变性的函数。
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:
上一个挑战介绍了 `concat` 方法,这是一种在不改变原始数组的前提下,将数组组合成新数组的方法。 将 `concat` 方法与 `push` 方法做比较。 `push` 将元素添加到调用它的数组的末尾,这样会改变该数组。 举个例子:
```js
var arr = [1, 2, 3];
arr.push([4, 5, 6]);
// arr is changed to [1, 2, 3, [4, 5, 6]]
// Not the functional programming way
```
`Concat` offers a way to add new items to the end of an array without any mutating side effects.
`arr` 的值被修改为 `[1, 2, 3, [4, 5, 6]]`,这不是函数编程方式。
`concat` 方法可以将新项目添加到数组末尾,而不产生副作用。
# --instructions--
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.
修改 `nonMutatingPush` 函数,用 `concat` 替代 `push``newItem` 添加到 `original` 末尾。 该函数应返回一个数组。
# --hints--
Your code should use the `concat` method.
应该使用 `concat` 方法。
```js
assert(code.match(/\.concat/g));
```
Your code should not use the `push` method.
不能使用 `push` 方法。
```js
assert(!code.match(/\.?[\s\S]*?push/g));
```
The `first` array should not change.
不能改变 `first` 数组。
```js
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
```
The `second` array should not change.
不能改变 `second` 数组。
```js
assert(JSON.stringify(second) === JSON.stringify([4, 5]));
```
`nonMutatingPush([1, 2, 3], [4, 5])` should return `[1, 2, 3, 4, 5]`.
`nonMutatingPush([1, 2, 3], [4, 5])` 应返回 `[1, 2, 3, 4, 5]`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7dab367417b2b2512b6d
title: Apply Functional Programming to Convert Strings to URL Slugs
title: 应用函数式编程将字符串转换为URL片段
challengeType: 1
forumTopicId: 301227
dashedName: apply-functional-programming-to-convert-strings-to-url-slugs
@ -8,45 +8,45 @@ dashedName: apply-functional-programming-to-convert-strings-to-url-slugs
# --description--
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`.
最后几个挑战中涵盖了许多符合函数式编程原则并在处理数组和字符串中非常有用的方法。 我们还学习了强大的、可以将问题简化为更简单形式的 `reduce` 方法。 从计算平均值到排序,任何数组操作都可以用它来实现。 回想一下,`map` `filter` 方法都是 `reduce` 的特殊实现。
Let's combine what we've learned to solve a practical problem.
让我们把学到的知识结合起来解决一个实际问题。
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.
许多内容管理站点CMS为了让添加书签更简单会将帖子的标题添加到 URL 上。 举个例子,如果你写了一篇标题为 `Stop Using Reduce` 的帖子URL很可能会包含标题字符串的某种形式 (如:`.../stop-using-reduce`)。 你可能已经在 freeCodeCamp 网站上注意到了这一点。
# --instructions--
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:
填写 `urlSlug` 函数,将字符串 `title` 转换成带有连字符号的 URL。 您可以使用本节中介绍的任何方法,但不要用 `replace` 方法。 以下是本次挑战的要求:
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--
Your code should not use the `replace` method for this challenge.
不能使用 `replace` 方法。
```js
assert(!code.match(/\.?[\s\S]*?replace/g));
```
`urlSlug("Winter Is Coming")` should return `"winter-is-coming"`.
`urlSlug("Winter Is Coming")` 应返回 `winter-is-coming`
```js
assert(urlSlug('Winter Is Coming') === 'winter-is-coming');
```
`urlSlug(" Winter Is Coming")` should return `"winter-is-coming"`.
`urlSlug(" Winter Is Coming")` 应返回 `winter-is-coming`
```js
assert(urlSlug(' Winter Is Coming') === 'winter-is-coming');
```
`urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")` should return `"a-mind-needs-books-like-a-sword-needs-a-whetstone"`.
`urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")` 应返回 `a-mind-needs-books-like-a-sword-needs-a-whetstone`
```js
assert(
@ -55,7 +55,7 @@ assert(
);
```
`urlSlug("Hold The Door")` should return `"hold-the-door"`.
`urlSlug("Hold The Door")` 应返回 `hold-the-door`
```js
assert(urlSlug('Hold The Door') === 'hold-the-door');

View File

@ -1,6 +1,6 @@
---
id: 587d7daa367417b2b2512b6c
title: Combine an Array into a String Using the join Method
title: 使用 join 方法将数组组合成字符串
challengeType: 1
forumTopicId: 18221
dashedName: combine-an-array-into-a-string-using-the-join-method
@ -8,47 +8,47 @@ dashedName: combine-an-array-into-a-string-using-the-join-method
# --description--
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.
`join` 方法用来把数组中的所有元素放入一个字符串。 并通过指定的分隔符参数进行分隔。
Here's an example:
举个例子:
```js
var arr = ["Hello", "World"];
var str = arr.join(" ");
// Sets str to "Hello World"
```
`str` 的值应该是字符串 `Hello World`
# --instructions--
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.
在函数 `sentensify` 内用 `join` 方法(及其他方法)用字符串 `str` 中的单词造句,这个函数应返回一个字符串。 该函数应返回一个数组。 举个例子,`I-like-Star-Wars` 会被转换成 `I like Star Wars`。 在此挑战中请勿使用 `replace` 方法。
# --hints--
Your code should use the `join` method.
应使用 `join` 方法。
```js
assert(code.match(/\.join/g));
```
Your code should not use the `replace` method.
不能使用 `replace` 方法。
```js
assert(!code.match(/\.?[\s\S]*?replace/g));
```
`sentensify("May-the-force-be-with-you")` should return a string.
`sentensify("May-the-force-be-with-you")` 应返回一个字符串。
```js
assert(typeof sentensify('May-the-force-be-with-you') === 'string');
```
`sentensify("May-the-force-be-with-you")` should return `"May the force be with you"`.
`sentensify("May-the-force-be-with-you")` 应返回 `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")` should return `"The force is strong with this one"`.
`sentensify("The.force.is.strong.with.this.one")` 应返回 `The force is strong with this one`
```js
assert(
@ -57,7 +57,7 @@ assert(
);
```
`sentensify("There,has,been,an,awakening")` should return `"There has been an awakening"`.
`sentensify("There,has,been,an,awakening")` 应返回 `There has been an awakening`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7da9367417b2b2512b66
title: Combine Two Arrays Using the concat Method
title: 使用 concat 方法组合两个数组
challengeType: 1
forumTopicId: 301229
dashedName: combine-two-arrays-using-the-concat-method
@ -8,38 +8,39 @@ dashedName: combine-two-arrays-using-the-concat-method
# --description--
<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:
<dfn>Concatenation</dfn> 意思是将元素连接到尾部。 同理JavaScript 为字符串和数组提供了`concat`方法。 对数组来说,在一个数组上调用 `concat` 方法,然后提供另一个数组作为参数添加到第一个数组末尾。 它返回一个新数组,不会改变任何一个原始数组。 举个例子:
```js
[1, 2, 3].concat([4, 5, 6]);
// Returns a new array [1, 2, 3, 4, 5, 6]
```
返回的数组将是 `[1, 2, 3, 4, 5, 6]`
# --instructions--
Use the `concat` method in the `nonMutatingConcat` function to concatenate `attach` to the end of `original`. The function should return the concatenated array.
`nonMutatingConcat` 函数里使用 `concat`,将 `attach` 拼接到 `original` 尾部。 函数返回拼接后的数组。
# --hints--
Your code should use the `concat` method.
应该使用 `concat` 方法。
```js
assert(code.match(/\.concat/g));
```
The `first` array should not change.
不应该改变 `first` 数组。
```js
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
```
The `second` array should not change.
不应该改变 `second` 数组。
```js
assert(JSON.stringify(second) === JSON.stringify([4, 5]));
```
`nonMutatingConcat([1, 2, 3], [4, 5])` should return `[1, 2, 3, 4, 5]`.
`nonMutatingConcat([1, 2, 3], [4, 5])` 应该返回 `[1, 2, 3, 4, 5]`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7dab367417b2b2512b70
title: 函数柯里化
title: 函数柯里化和局部调用
challengeType: 1
forumTopicId: 301232
dashedName: introduction-to-currying-and-partial-application
@ -8,7 +8,7 @@ dashedName: introduction-to-currying-and-partial-application
# --description--
<dfn>arity</dfn> 是函数所需的形参的数量。 函数柯里化(<dfn>Currying</dfn>)意思是把接受多个 arity 的函数变换成接受单一arity 的函数。
<dfn>arity</dfn>(参数个数)是函数所需的形参的数量。 函数柯里化(<dfn>Currying</dfn>)意思是把接受多个 arity 的函数变换成接受单一 arity 的函数。
换句话说,就是重构函数让它接收一个参数,然后返回接收下一个参数的函数,依此类推。

View File

@ -1,6 +1,6 @@
---
id: 587d7b8e367417b2b2512b5f
title: Pass Arguments to Avoid External Dependence in a Function
title: 传递参数以避免函数中的外部依赖
challengeType: 1
forumTopicId: 301234
dashedName: pass-arguments-to-avoid-external-dependence-in-a-function
@ -8,39 +8,39 @@ 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.
上一个挑战是更接近函数式编程原则的挑战,但是仍然缺少一些东西。
We didn't alter the global variable value, but the function `incrementer` would not work without the global variable `fixedValue` being there.
虽然我们没有改变全局变量值,但在没有全局变量 `fixedValue` 的情况下,`incrementer` 函数将不起作用。
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--
Let's update the `incrementer` function to clearly declare its dependencies.
更新 `incrementer` 函数,明确声明其依赖项。
Write the `incrementer` function so it takes an argument, and then returns a result after increasing the value by one.
编写 `incrementer` 函数,获取它的参数,然后将值增加 1。
# --hints--
Your function `incrementer` should not change the value of `fixedValue` (which is `4`).
`incrementer` 函数不能修改 `fixedValue` 的值(它的值是 `4`)。
```js
assert(fixedValue === 4);
```
Your `incrementer` function should take an argument.
`incrementer` 函数应该接收一个参数。
```js
assert(incrementer.length === 1);
```
Your `incrementer` function should return a value that is one larger than the `fixedValue` value.
`incrementer` 函数应返回比 `fixedValue` 更大的值。
```js
const __newValue = incrementer(fixedValue);

View File

@ -1,6 +1,6 @@
---
id: 587d7da9367417b2b2512b6a
title: Return a Sorted Array Without Changing the Original Array
title: 在不更改原始数组的前提下返回排序后的数组
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--
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.
`sort` 方法会产生改变原始数组中元素顺序的副作用。 换句话说,它会改变数组的位置。 避免这种情况的一种方法是先将空数组连接到正在排序的数组上(记住 `slice` `concat` 返回一个新数组),再用`sort`方法。
# --instructions--
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.
`nonMutatingSort` 函数中使用 `sort` 方法对数组中的元素按升序进行排列。 函数不能改变 `globalArray` 变量,应返回一个新数组。
# --hints--
Your code should use the `sort` method.
应该使用 `sort` 方法。
```js
assert(nonMutatingSort.toString().match(/\.sort/g));
```
The `globalArray` variable should not change.
`globalArray` 变量不应该改变。
```js
assert(JSON.stringify(globalArray) === JSON.stringify([5, 6, 3, 2, 9]));
```
`nonMutatingSort(globalArray)` should return `[2, 3, 5, 6, 9]`.
`nonMutatingSort(globalArray)` 应该返回 `[2, 3, 5, 6, 9]`
```js
assert(
@ -37,18 +37,32 @@ assert(
);
```
`nonMutatingSort(globalArray)` should not be hard coded.
`nonMutatingSort(globalArray)` 不应被硬编码。
```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);
```
`nonMutatingSort([1, 30, 4, 21, 100000])` 应该返回 `[1, 4, 21, 30, 100000]`
```js
assert(JSON.stringify(nonMutatingSort([1, 30, 4, 21, 100000])) ===
JSON.stringify([1, 4, 21, 30, 100000]))
```
`nonMutatingSort([140000, 104, 99])` 应该返回 `[99, 104, 140000]`
```js
assert(JSON.stringify(nonMutatingSort([140000, 104, 99])) ===
JSON.stringify([99, 104, 140000]))
```
# --seed--
## --seed-contents--

View File

@ -1,6 +1,6 @@
---
id: 587d7da9367417b2b2512b69
title: Sort an Array Alphabetically using the sort Method
title: 使用 sort 方法按字母顺序给数组排序
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--
The `sort` method sorts the elements of an array according to the callback function.
`sort` 方法可以根据回调函数对数组元素进行排序。
For example:
举个例子:
```js
function ascendingOrder(arr) {
@ -19,32 +19,36 @@ function ascendingOrder(arr) {
});
}
ascendingOrder([1, 5, 2, 3, 4]);
// Returns [1, 2, 3, 4, 5]
```
这将返回值 `[1, 2, 3, 4, 5]`
```js
function reverseAlpha(arr) {
return arr.sort(function(a, b) {
return a === b ? 0 : a < b ? 1 : -1;
});
}
reverseAlpha(['l', 'h', 'z', 'b', 's']);
// Returns ['z', 's', 'l', 'h', '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.
这将返回值 `['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` 的位置保持不变。
# --instructions--
Use the `sort` method in the `alphabeticalOrder` function to sort the elements of `arr` in alphabetical order.
`alphabeticalOrder` 函数中使用 `sort` 方法对 `arr` 中的元素按照字母顺序排列。
# --hints--
Your code should use the `sort` method.
应该使用 `sort` 方法。
```js
assert(code.match(/\.sort/g));
```
`alphabeticalOrder(["a", "d", "c", "a", "z", "g"])` should return `["a", "a", "c", "d", "g", "z"]`.
`alphabeticalOrder(["a", "d", "c", "a", "z", "g"])` 应返回 `["a", "a", "c", "d", "g", "z"]`
```js
assert(
@ -53,7 +57,7 @@ assert(
);
```
`alphabeticalOrder(["x", "h", "a", "m", "n", "m"])` should return `["a", "h", "m", "m", "n", "x"]`.
`alphabeticalOrder(["x", "h", "a", "m", "n", "m"])`应返回`["a", "h", "m", "m", "n", "x"]`
```js
assert(
@ -62,7 +66,7 @@ assert(
);
```
`alphabeticalOrder(["a", "a", "a", "a", "x", "t"])` should return `["a", "a", "a", "a", "t", "x"]`.
`alphabeticalOrder(["a", "a", "a", "a", "x", "t"])` 应返回 `["a", "a", "a", "a", "t", "x"]`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7daa367417b2b2512b6b
title: Split a String into an Array Using the split Method
title: 使用 split 方法将字符串拆分成数组
challengeType: 1
forumTopicId: 18305
dashedName: split-a-string-into-an-array-using-the-split-method
@ -8,35 +8,35 @@ dashedName: split-a-string-into-an-array-using-the-split-method
# --description--
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.
`split` 方法将一个字符串分割成一个字符串数组。 它需要一个参数作为分隔符,它可以是用于拆分字符串或正则表达式的一个字符。 举个例子,如果分隔符是空格,你会得到一个单词数组;如果分隔符是空字符串,你会得到一个由字符串中每个字符组成的数组。
Here are two examples that split one string by spaces, then another by digits using a regular expression:
下面是两个用空格分隔一个字符串的例子,另一个是用数字的正则表达式分隔:
```js
var str = "Hello World";
var bySpace = str.split(" ");
// Sets bySpace to ["Hello", "World"]
var otherString = "How9are7you2today";
var byDigits = otherString.split(/\d/);
// Sets byDigits to ["How", "are", "you", "today"]
```
Since strings are immutable, the `split` method makes it easier to work with them.
`bySpace` 将有值 `["Hello", "World"]``byDigits` 将有值 `["How", "are", "you", "today"]`
因为字符串是不可变的,`split` 方法操作它们更方便。
# --instructions--
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.
`splitify` 函数中用 `split` 方法将 `str` 分割成单词数组。 这个方法应该返回一个数组。 单词不一定都是用空格分隔,所以数组中不应包含标点符号。
# --hints--
Your code should use the `split` method.
应该使用 `split` 方法。
```js
assert(code.match(/\.split/g));
```
`splitify("Hello World,I-am code")` should return `["Hello", "World", "I", "am", "code"]`.
`splitify("Hello World,I-am code")` 应返回 `["Hello", "World", "I", "am", "code"]`
```js
assert(
@ -45,7 +45,7 @@ assert(
);
```
`splitify("Earth-is-our home")` should return `["Earth", "is", "our", "home"]`.
`splitify("Earth-is-our home")` 应返回 `["Earth", "is", "our", "home"]`
```js
assert(
@ -54,7 +54,7 @@ assert(
);
```
`splitify("This.is.a-sentence")` should return `["This", "is", "a", "sentence"]`.
`splitify("This.is.a-sentence")` 应返回 `["This", "is", "a", "sentence"]`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b8e367417b2b2512b5c
title: Understand Functional Programming Terminology
title: 了解函数式编程术语
challengeType: 1
forumTopicId: 301240
dashedName: understand-functional-programming-terminology
@ -8,47 +8,47 @@ dashedName: understand-functional-programming-terminology
# --description--
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.
FCC 团队需求有变更,现在想要两种茶:绿茶(green tea)和红茶(black tea)。 事实证明,用户需求变更是很常见的。
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.
基于以上信息,我们需要重构上一节挑战中的 `getTea` 函数来处理多种茶的请求。 我们可以修改 `getTea` 接受一个函数作为参数,使它能够修改茶的类型。 这让 `getTea` 更灵活,也使需求变更时为程序员提供更多控制权。
But first, let's cover some functional terminology:
首先,我们将介绍一些术语:
<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.
<dfn>Callbacks</dfn> 是被传递到另一个函数中调用的函数。 你应该已经在其他函数中看过这个写法,例如在 `filter` 中,回调函数告诉 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.
函数就像其他正常值一样,可以赋值给变量、传递给另一个函数,或从其它函数返回,这种函数叫做头等 <dfn>first class</dfn> 函数。 在 JavaScript 中,所有函数都是头等函数。
The functions that take a function as an argument, or return a function as a return value are called <dfn>higher order</dfn> functions.
将函数为参数或返回值的函数叫做高阶 ( <dfn>higher order</dfn>) 函数。
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>.
当函数传递给另一个函数或从另一个函数返回时,那些传入或返回的函数可以叫做<dfn>lambda</dfn>
# --instructions--
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.
准备 27 杯绿茶和 13 杯红茶,分别存入 `tea4GreenTeamFCC` `tea4BlackTeamFCC` 变量。 请注意,`getTea` 函数已经变了,现在它接收一个函数作为第一个参数。
Note: The data (the number of cups of tea) is supplied as the last argument. We'll discuss this more in later lessons.
注意:数据(茶的数量)作为最后一个参数。 我们将在后面的课程中对此进行更多讨论。
# --hints--
The `tea4GreenTeamFCC` variable should hold 27 cups of green tea for the team.
`tea4GreenTeamFCC` 变量应存有为团队准备的 27 杯茶。
```js
assert(tea4GreenTeamFCC.length === 27);
```
The `tea4GreenTeamFCC` variable should hold cups of green tea.
`tea4GreenTeamFCC` 变量应存有绿茶。
```js
assert(tea4GreenTeamFCC[0] === 'greenTea');
```
The `tea4BlackTeamFCC` variable should hold 13 cups of black tea.
`tea4BlackTeamFCC` 变量应存有 13 杯红茶。
```js
assert(tea4BlackTeamFCC.length === 13);
```
The `tea4BlackTeamFCC` variable should hold cups of black tea.
`tea4BlackTeamFCC` 变量应存有红茶。
```js
assert(tea4BlackTeamFCC[0] === 'blackTea');

View File

@ -1,6 +1,6 @@
---
id: 587d7b8e367417b2b2512b5d
title: Understand the Hazards of Using Imperative Code
title: 了解使用命令式编程的危害
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--
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.
使用函数式编程是一个好的习惯。 它使你的代码易于管理,避免潜在的 bug。 但在开始之前,先看看命令式编程方法,以强调你可能有什么问题。
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.
在英语 (以及许多其他语言) 中,命令式时态用来发出指令。 同样,命令式编程是向计算机提供一套执行任务的声明。
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.
命令式编程常常改变程序状态,例如更新全局变量。 一个典型的例子是编写 `for` 循环,它为一个数组的索引提供了准确的迭代方向。
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 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.
JavaScript 提供了许多处理常见任务的方法,所以你无需写出计算机应如何执行它们。 例如,你可以用 `map` 函数替代上面提到的 `for` 循环来处理数组迭代。 这有助于避免语义错误,如调试章节介绍的 "Off By One Errors"。
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.
窗口对象由选项卡组成,通常会打开多个窗口。 窗口对象中每个打开网站的标题都保存在一个数组中。 在对浏览器进行了如打开新标签、合并窗口、关闭标签之类的操作后,你需要输出所有打开的标签。 关掉的标签将从数组中删除,新打开的标签(为简单起见)则添加到数组的末尾。
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.
代码编辑器中显示了此功能的实现,其中包含 `tabOpen()``tabClose()`,和 `join()` 函数。 `tabs` 数组是窗口对象的一部分用于储存打开页面的名称。
# --instructions--
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.
在编辑器中运行代码。 它使用了有副作用的方法,导致输出错误。 存储在 `finalTabs.tabs` 中的打开标签的最终列表应该是 `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']`,但输出会略有不同。
Change `Window.prototype.tabClose` so that it removes the correct tab.
修改 `Window.prototype.tabClose` 使其删除正确的标签。
# --hints--
`finalTabs.tabs` should be `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']`
`finalTabs.tabs` 应该是 `['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: 'Use Higher-Order Functions map, filter, or reduce to Solve a Complex Problem'
title: '使用高阶函数 mapfilter 或者 reduce 来解决复杂问题'
challengeType: 1
forumTopicId: 301311
dashedName: use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-problem
@ -8,30 +8,30 @@ dashedName: use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-p
# --description--
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.
已经接触了高阶函数如 `map()` `filter()` `reduce()`的使用,是时候用它们来完成一些复杂的挑战了。
# --instructions--
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]`.
已经定义了一个函数 `squareList`。 你需要使用 `map()``filter()` `reduce()` 的任意组合来完成 `squareList` 函数的代码。当传入一个实数数组时,返回一个*仅*包含正整数(小数不是整数)的平方的新数组。 仅包含实数字的数组示例是 `[-3, 4.8, 5, 3, -3.2]`
**Note:** Your function should not use any kind of `for` or `while` loops or the `forEach()` function.
**注意:** 函数不应该包含任何形式的 `for` 或者 `while` 循环或者 `forEach()` 函数。
# --hints--
`squareList` should be a `function`.
`squareList` 应该是一个 `function`
```js
assert.typeOf(squareList, 'function'),
'<code>squareList</code> should be a <code>function</code>';
```
`for`, `while`, and `forEach` should not be used.
不应该使用 `for``while` 或者 `forEach`
```js
assert(!__helpers.removeJSComments(code).match(/for|while|forEach/g));
```
`map`, `filter`, or `reduce` should be used.
应该使用 `map``filter` 或者 `reduce`
```js
assert(
@ -41,13 +41,13 @@ assert(
);
```
The function should return an `array`.
函数应该返回 `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])` should return `[16, 1764, 36]`.
`squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])` 应该返回 `[16, 1764, 36]`
```js
assert.deepStrictEqual(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]), [
@ -57,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])` should return `[9, 100, 49]`.
`squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3])` 应该返回 `[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: Use the every Method to Check that Every Element in an Array Meets a Criteria
title: 使用 every 方法检查数组中的每个元素是否符合条件
challengeType: 1
forumTopicId: 301312
dashedName: use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria
@ -8,43 +8,44 @@ dashedName: use-the-every-method-to-check-that-every-element-in-an-array-meets-a
# --description--
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.
`every` 方法用于检测数组中*所有*元素是否都符合指定条件。 如果所有元素满足条件,返回布尔值 `true`,反之返回 `false`
For example, the following code would check if every element in the `numbers` array is less than 10:
举个例子,下面的代码检测数组 `numbers` 的所有元素是否都小于 10
```js
var numbers = [1, 5, 8, 0, 10, 11];
numbers.every(function(currentValue) {
return currentValue < 10;
});
// Returns false
```
`every` 方法在这里会返回 `false`
# --instructions--
Use the `every` method inside the `checkPositive` function to check if every element in `arr` is positive. The function should return a Boolean value.
`checkPositive` 函数中使用 `every` 方法检查 `arr` 中是否所有元素都是正数。 函数应返回一个布尔值。
# --hints--
Your code should use the `every` method.
应使用`every`方法。
```js
assert(code.match(/\.every/g));
```
`checkPositive([1, 2, 3, -4, 5])` should return `false`.
`checkPositive([1, 2, 3, -4, 5])` 应返回 `false`
```js
assert.isFalse(checkPositive([1, 2, 3, -4, 5]));
```
`checkPositive([1, 2, 3, 4, 5])` should return `true`.
`checkPositive([1, 2, 3, 4, 5])` 应返回 `true`
```js
assert.isTrue(checkPositive([1, 2, 3, 4, 5]));
```
`checkPositive([1, -2, 3, -4, 5])` should return `false`.
`checkPositive([1, -2, 3, -4, 5])` 应返回 `false`
```js
assert.isFalse(checkPositive([1, -2, 3, -4, 5]));

View File

@ -1,6 +1,6 @@
---
id: 587d7b8f367417b2b2512b63
title: Use the filter Method to Extract Data from an Array
title: 使用 filter 方法从数组中提取数据
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--
Another useful array function is `Array.prototype.filter()`, or simply `filter()`.
另一个有用的数组方法是 `filter()`(即 `Array.prototype.filter()`)。
`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` 接收一个回调函数,将回调函数内的逻辑应用于数组的每个元素,新数组包含根据回调函数内条件返回 `true` 的元素。 换言之,它根据传递给它的函数过滤数组。 和 `map` 一样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.
回调函数接收三个参数。 第一个参数是当前正在被处理的元素。 第二个参数是这个元素的索引,第三个参数是在其上调用 `filter` 方法的数组。
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.
看下在 `users` 上使用 `filter` 方法的例子,返回了一个包含了 30 岁以下的用户新数组。 为了简化,例子里只使用了回调函数的第一个参数。
```js
const users = [
@ -24,16 +24,18 @@ const users = [
];
const usersUnder30 = users.filter(user => user.age < 30);
console.log(usersUnder30); // [ { name: 'Amy', age: 20 }, { name: 'camperCat', age: 10 } ]
console.log(usersUnder30);
```
控制台将显示值 `[ { name: 'Amy', age: 20 }, { name: 'camperCat', age: 10 } ]`
# --instructions--
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.
`watchList` 变量中包含一组存有多部电影信息对象。 结合 `filter` `map` 返回一个 `watchList` 只包含 `title` `rating` 属性的新数组。 新数组只包含 `imdbRating` 值大于或等于 8.0 的对象。 请注意,`rating` 值在对象中保存为字符串,你可能需要将它转换成数字来执行运算。
# --hints--
The `watchList` variable should not change.
`watchList`应保持不变。
```js
assert(
@ -41,19 +43,19 @@ assert(
);
```
Your code should use the `filter` method.
应使用 `filter` 方法。
```js
assert(code.match(/\.filter/g));
```
Your code should not use a `for` loop.
不能使用 `for` 循环。
```js
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
```
`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"}]`.
`filteredList` 应等于 `[{"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: Use the map Method to Extract Data from an Array
title: 使用 map 方法从数组中提取数据
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.
这仅仅是个开始。 顾名思义,函数式编程以函数理论为中心。
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.
能够将它们作为参数传递给其他函数,从另一个函数返回一个函数是有意义的。 函数在 JavaScript 中被视为 <dfn>First Class Objects</dfn>,它们可以像任何其他对象一样使用。 它们可以保存在变量中,存储在对象中,也可以作为函数参数传递。
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` 方法(即 `Array.prototype.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.
当调用回调函数时,传入了三个参数。 第一个参数是当前正在处理的数组项。 第二个参数是当前数组项的索引值,第三个参数是在其上调用 `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.
看下在 `users` 上使用 `map` 方法的例子,返回了一个新数组只包含了用户的名字。 为了简化,例子里只使用了回调函数的第一个参数。
```js
const users = [
@ -30,16 +30,18 @@ const users = [
];
const names = users.map(user => user.name);
console.log(names); // [ 'John', 'Amy', 'camperCat' ]
console.log(names);
```
控制台将显示值 `[ 'John', 'Amy', 'camperCat' ]`
# --instructions--
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.
`watchList` 数组保存了包含一些电影信息的对象。 使用 `map` `watchList` 中提取标题(`title`)和评分(`rating`),并将新数组保存在 `ratings` 变量里。 目前编辑器中的代码是使用 `for` 循环实现,使用 `map` 表达式替换循环功能。
# --hints--
The `watchList` variable should not change.
`watchList` 应保持不变。
```js
assert(
@ -47,19 +49,19 @@ assert(
);
```
Your code should not use a `for` loop.
不能使用 `for` 循环。
```js
assert(!__helpers.removeJSComments(code).match(/for\s*?\([\s\S]*?\)/));
```
Your code should use the `map` method.
你的代码应使用 `map` 方法。
```js
assert(code.match(/\.map/g));
```
`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"}]`.
`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"}]`
```js
assert.deepEqual(ratings, [

View File

@ -1,6 +1,6 @@
---
id: 587d7da9367417b2b2512b68
title: Use the reduce Method to Analyze Data
title: 使用 reduce 方法分析数据
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--
`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()`(即`Array.prototype.reduce()`),是 JavaScript 所有数组操作中最常用的方法。 几乎可以用`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`方法是处理数组更通用的方式,而且`filter``map`方法都可以当作是`reduce`的特殊实现。 `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.
除了回调函数,`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.
见下面的例子,给 `users` 数组使用 `reduce` 方法,返回所有用户数组的和。 为了简化,例子仅使用了回调函数的第一个参数和第二个参数。
```js
const users = [
@ -26,10 +26,12 @@ const users = [
];
const sumOfAges = users.reduce((sum, user) => sum + user.age, 0);
console.log(sumOfAges); // 64
console.log(sumOfAges);
```
In another example, see how an object can be returned containing the names of the users as properties with their ages as values.
这里控制台将显示值 `64`
在另一个例子里,查看如何返回一个包含用户名称做为属性,其年龄做为值的对象。
```js
const users = [
@ -42,16 +44,18 @@ const usersObj = users.reduce((obj, user) => {
obj[user.name] = user.age;
return obj;
}, {});
console.log(usersObj); // { John: 34, Amy: 20, camperCat: 10 }
console.log(usersObj);
```
控制台将显示值 `{ John: 34, Amy: 20, camperCat: 10 }`
# --instructions--
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.
`watchList` 是包含一些电影信息的对象。 使用 `reduce` 查找由 `Christopher Nolan` 导演的电影的 IMDB 评级平均值。 回想一下之前的挑战,如何 `filter` 数据,以及使用 `map` 来获取你想要的数据。 您可能需要创建其他变量,并从 `getRating` 函数返回平均评分。 请注意,评级在对象中是字符串,需要将其转换为数字再用于数学运算。
# --hints--
The `watchList` variable should not change.
`watchList` 应保持不变。
```js
assert(
@ -59,25 +63,25 @@ assert(
);
```
Your code should use the `reduce` method.
应该使用`reduce`方法。
```js
assert(code.match(/\.reduce/g));
```
The `getRating(watchList)` should equal 8.675.
`getRating(watchList)` 应该等于 8.675
```js
assert(getRating(watchList) === 8.675);
```
Your code should not use a `for` loop.
不能使用 `for` 循环。
```js
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
```
Your code should return correct output after modifying the `watchList` object.
在修改 `watchList` 对象后应该返回正确的输出。
```js
assert(getRating(watchList.filter((_, i) => i < 1 || i > 2)) === 8.55);

View File

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