fix(i18n): update Chinese translation of functional programming (#38061)

* fix(i18n): update Chinese translation of functional programming

* fix(i18n): update review suggestion

Co-authored-by: Zhicheng Chen <chenzhicheng@dayuwuxian.com>
This commit is contained in:
ZhichengChen
2020-08-05 16:38:04 +08:00
committed by GitHub
parent ebcb34f3d9
commit 1046e21a90
24 changed files with 1595 additions and 585 deletions

View File

@ -2,30 +2,44 @@
id: 587d7da9367417b2b2512b67
title: Add Elements to the End of an Array Using concat Instead of push
challengeType: 1
videoUrl: ''
localeTitle: 使用concat将元素添加到数组的末尾而不是push
forumTopicId: 301226
localeTitle: 使用 concat 而不是 push 将元素添加到数组的末尾
---
## Description
<section id="description">函数式编程就是创建和使用非变异函数。最后一个挑战是将<code>concat</code>方法作为一种将数组组合成新数组而不改变原始数组的方法。将<code>concat</code><code>push</code>方法进行比较。 <code>Push</code>将一个项添加到调用它的同一个数组的末尾,这会改变该数组。这是一个例子: <blockquote> var arr = [1,2,3]; <br> arr.push[4,5,6]; <br> // arr更改为[1,2,3[4,5,6]] <br> //不是函数式编程方式</blockquote> <code>Concat</code>提供了一种在数组末尾添加新项目而无任何变异副作用的方法。 </section>
<section id='description'>
函数式编程就是创建和使用具有不变性的函数。
上一个挑战介绍了<code>concat</code>方法,这是一种在不改变原始数组的前提下,将数组组合成新数组的方法。将<code>concat</code>方法与<code>push</code>方法做比较,<code>Push</code>将元素添加到调用它的数组的末尾,这样会改变该数组。举个例子:
```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
```
<code>Concat</code>方法可以将新项目添加到数组末尾,而不产生任何变化。
</section>
## Instructions
<section id="instructions">更改<code>nonMutatingPush</code>函数,使其使用<code>concat</code><code>newItem</code>添加到<code>original</code>结尾而不是<code>push</code> 。该函数应返回一个数组。 </section>
<section id='instructions'>
修改<code>nonMutatingPush</code>函数,用<code>concat</code>替代<code>push</code><code>newItem</code>添加到<code>original</code>末尾,该函数应返回一个数组。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 您的代码应使用<code>concat</code>方法。
- text: 使用<code>concat</code>方法。
testString: assert(code.match(/\.concat/g));
- text: 您的代码不应使用<code>push</code>方法。
- text: 不能使用<code>push</code>方法。
testString: assert(!code.match(/\.push/g));
- text: <code>first</code>数组不应该改变
- text: 不能改变<code>first</code>数组。
testString: assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
- text: <code>second</code>数组不应该改变
- text: 不能改变<code>second</code>数组。
testString: assert(JSON.stringify(second) === JSON.stringify([4, 5]));
- text: '<code>nonMutatingPush([1, 2, 3], [4, 5])</code>应返回<code>[1, 2, 3, 4, 5]</code> 。'
- text: <code>nonMutatingPush([1, 2, 3], [4, 5])</code>应返回<code>[1, 2, 3, 4, 5]</code>
testString: assert(JSON.stringify(nonMutatingPush([1, 2, 3], [4, 5])) === JSON.stringify([1, 2, 3, 4, 5]));
```
@ -47,7 +61,6 @@ function nonMutatingPush(original, newItem) {
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingPush(first, second);
```
</div>
@ -60,6 +73,12 @@ nonMutatingPush(first, second);
<section id='solution'>
```js
// solution required
function nonMutatingPush(original, newItem) {
return original.concat(newItem);
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingPush(first, second);
```
</section>

View File

@ -2,32 +2,42 @@
id: 587d7dab367417b2b2512b6d
title: Apply Functional Programming to Convert Strings to URL Slugs
challengeType: 1
videoUrl: ''
localeTitle: 应用函数式编程将字符串转换为URL Slugs
forumTopicId: 301227
localeTitle: 应用函数式编程将字符串转换为URL片段
---
## Description
<section id="description">最后几个挑战涵盖了许多遵循函数式编程原理的有用数组和字符串方法。我们还学习了<code>reduce</code> ,这是一种用于将问题简化为更简单形式的强大方法。从计算平均值到排序,可以通过应用它来实现任何阵列操作。回想一下<code>map</code><code>filter</code><code>reduce</code>特例。让我们结合我们学到的东西来解决实际问题。许多内容管理站点CMS将帖子的标题添加到URL的一部分以用于简单的书签目的。例如如果您编写一个标题为“Stop Using Reduce”的Medium帖子则URL可能会包含某种形式的标题字符串“... / stop-using-reduce”。您可能已经在freeCodeCamp网站上注意到了这一点。 </section>
<section id='description'>
最后几个挑战中涵盖了许多符合函数式编程原则并在处理数组和字符串中非常有用的方法。我们还学习了强大的、可以将问题简化为更简单形式的<code>reduce</code>方法,从计算平均值到排序,任何数组操作都可以用它来实现。回想一下,<code>map</code><code>filter</code>方法都是<code>reduce</code>的特殊实现。
让我们把学到的知识结合起来解决一个实际问题。
许多内容管理站点CMS为了让添加书签更简单会将帖子的标题添加到 URL 上。举个例子,如果你写了一篇标题为 "Stop Using Reduce" 的帖子URL很可能会包含标题字符串的某种形式 (如:".../stop-using-reduce"),你可能已经在 freeCodeCamp 网站上注意到了这一点。
</section>
## Instructions
<section id="instructions">填写<code>urlSlug</code>函数,以便转换字符串<code>title</code>并返回URL的连字符版本。您可以使用本节中介绍的任何方法也不要使用<code>replace</code> 。以下是要求:输入是一个带空格和标题字的字符串输出是一个字符串,单词之间的空格用连字符替换( <code>-</code> )输出应该是所有低位字母输出不应该有任何空格</section>
<section id='instructions'>
填写<code>urlSlug</code>函数,将字符串<code>title</code>转换成带有连字符号的 URL。您可以使用本节中介绍的任何方法但不要用<code>replace</code>方法。以下是本次挑战的要求:
输入包含空格和标题大小写单词的字符串
输出字符串,单词之间的空格用连字符(<code>-</code>)替换
输出应该是小写字母
输出不应有任何空格
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>globalTitle</code>变量不应该更改
- text: <code>globalTitle</code>变量应保持不变
testString: assert(globalTitle === "Winter Is Coming");
- text: 您的代码不应使用<code>replace</code>方法来应对此挑战
- text: 在此挑战中不能使用<code>replace</code>方法。
testString: assert(!code.match(/\.replace/g));
- text: <code>urlSlug(&quot;Winter Is Coming&quot;)</code>应该回归<code>&quot;winter-is-coming&quot;</code>
- text: "<code>urlSlug('Winter Is Coming')</code>应返回<code>'winter-is-coming'</code>。"
testString: assert(urlSlug("Winter Is Coming") === "winter-is-coming");
- text: <code>urlSlug(&quot; Winter Is Coming&quot;)</code>应该回归<code>&quot;winter-is-coming&quot;</code>
- text: "<code>urlSlug(' Winter Is &nbsp;Coming')</code>应返回<code>'winter-is-coming'</code>。"
testString: assert(urlSlug(" Winter Is Coming") === "winter-is-coming");
- text: <code>urlSlug(&quot;A Mind Needs Books Like A Sword Needs A Whetstone&quot;)</code>应该回归<code>&quot;a-mind-needs-books-like-a-sword-needs-a-whetstone&quot;</code>
- text: "<code>urlSlug('A Mind Needs Books Like A Sword Needs A Whetstone')</code>应返回<code>'a-mind-needs-books-like-a-sword-needs-a-whetstone'</code>。"
testString: assert(urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone") === "a-mind-needs-books-like-a-sword-needs-a-whetstone");
- text: <code>urlSlug(&quot;Hold The Door&quot;)</code>应返回<code>&quot;hold-the-door&quot;</code>
- text: "<code>urlSlug('Hold The Door')</code>应返回<code>'hold-the-door'</code>。"
testString: assert(urlSlug("Hold The Door") === "hold-the-door");
```
@ -51,7 +61,6 @@ function urlSlug(title) {
// Add your code above this line
var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"
```
</div>
@ -64,6 +73,16 @@ var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"
<section id='solution'>
```js
// solution required
// the global variable
var globalTitle = "Winter Is Coming";
// Add your code below this line
function urlSlug(title) {
return title.trim().split(/\s+/).join("-").toLowerCase();
}
// Add your code above this line
var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"
```
</section>

View File

@ -2,24 +2,33 @@
id: 587d7b8e367417b2b2512b5e
title: Avoid Mutations and Side Effects Using Functional Programming
challengeType: 1
videoUrl: ''
localeTitle: 使用功能编程避免变和副作用
forumTopicId: 301228
localeTitle: 使用函数式编程避免变和副作用
---
## Description
<section id="description">如果您还没有弄明白,上一次挑战中的问题是使用<code>tabClose()</code>函数中的<code>splice</code>调用。不幸的是, <code>splice</code>更改了它所调用的原始数组,因此对它的第二次调用使用了一个修改过的数组,并给出了意想不到的结果。这是一个更大模式的一个小例子 - 你在一个变量,数组或一个对象上调用一个函数,该函数改变了对象中的变量或其他东西。函数式编程的核心原则之一是不改变事物。变化导致错误。知道你的函数不会改变任何东西,包括函数参数或任何全局变量,更容易防止错误。前面的例子没有任何复杂的操作,但是<code>splice</code>方法改变了原始数组并导致了一个bug。回想一下在函数式编程中改变或改变事物称为<code>mutation</code> ,结果称为<code>side effect</code> 。理想情况下,函数应该是<code>pure function</code> ,这意味着它不会产生任何副作用。让我们尝试掌握这门学科,不要改变代码中的任何变量或对象。 </section>
<section id='description'>
如果你还没想通,上一个挑战的问题出在<code>tabClose()</code>函数里的<code>splice</code>。不幸的是,<code>splice</code>修改了调用它的原始数组,所以第二次调用它时是基于修改后的数组,才给出了意料之外的结果。
这是一个小例子,还有更广义的定义——在变量,数组或对象上调用一个函数,这个函数会改变对象中的变量或其他东西。
函数式编程的核心原则之一是不改变任何东西。变化会导致错误。如果一个函数不改变传入的参数、全局变量等数据,那么它造成问题的可能性就会小很多。
前面的例子没有任何复杂的操作,但是<code>splice</code>方法改变了原始数组,导致 bug 产生。
回想一下,在函数式编程中,改变或变更叫做<code>mutation</code>,这种改变的结果叫做“副作用”(<code>side effect</code>)。理想情况下,函数应该是不会产生任何副作用的<code>纯函数</code>
让我们尝试掌握这个原则:不要改变代码中的任何变量或对象。
</section>
## Instructions
<section id="instructions">填写函数<code>incrementer</code>的代码,使其返回全局变量<code>fixedValue</code>的值增加1。 </section>
<section id='instructions'>
填写<code>incrementer</code>函数的代码,使其返回全局变量<code>fixedValue</code>的值增加 1。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 您的函数<code>incrementer</code>不应更改<code>fixedValue</code>的值。
- text: <code>incrementer</code>函数不能改变<code>fixedValue</code>的值。
testString: assert(fixedValue === 4);
- text: 您的<code>incrementer</code>函数应返回一个大于<code>fixedValue</code>的值。
- text: <code>incrementer</code>函数应返回<code>fixedValue</code>变量更大的值。
testString: assert(newValue === 5);
```
@ -44,7 +53,6 @@ function incrementer () {
var newValue = incrementer(); // Should equal 5
console.log(fixedValue); // Should print 4
```
</div>
@ -57,6 +65,13 @@ console.log(fixedValue); // Should print 4
<section id='solution'>
```js
// solution required
var fixedValue = 4
function incrementer() {
return fixedValue + 1
}
var newValue = incrementer(); // Should equal 5
```
</section>

View File

@ -2,32 +2,44 @@
id: 587d7daa367417b2b2512b6c
title: Combine an Array into a String Using the join Method
challengeType: 1
videoUrl: ''
localeTitle: 使用join方法将Array组合成String
forumTopicId: 18221
localeTitle: 使用 join 方法将数组组合成字符串
---
## Description
<section id="description"> <code>join</code>方法用于将数组的元素连接在一起以创建字符串。它需要一个用于分隔字符串中数组元素的分隔符的参数。这是一个例子: <blockquote> var arr = [“你好”,“世界”]; <br> var str = arr.join“”; <br> //将str设置为“Hello World” </blockquote></section>
<section id='description'>
<code>join</code>方法用来把数组中的所有元素放入一个字符串,并通过指定的分隔符参数进行分隔。
举个例子:
```js
var arr = ["Hello", "World"];
var str = arr.join(" ");
// Sets str to "Hello World"
```
</section>
## Instructions
<section id="instructions">使用<code>sentensify</code>函数内的<code>join</code>方法(以及其他方法)从字符串<code>str</code>的单词创建一个句子。该函数应返回一个字符串。例如,“我喜欢星球大战”将被转换为“我喜欢星球大战”。对于此挑战,请勿使用<code>replace</code>方法。 </section>
<section id='instructions'>
在函数<code>sentensify</code>内用<code>join</code>方法(及其他方法)用字符串<code>str</code>中的单词造句,这个函数应返回一个字符串。举个例子,"I-like-Star-Wars" 会被转换成 "I like Star Wars"。在此挑战中请勿使用<code>replace</code>方法。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 您的代码应使用<code>join</code>方法。
- text: 应使用<code>join</code>方法。
testString: assert(code.match(/\.join/g));
- text: 您的代码不应使用<code>replace</code>方法。
- text: 不能使用<code>replace</code>方法。
testString: assert(!code.match(/\.replace/g));
- text: <code>sentensify(&quot;May-the-force-be-with-you&quot;)</code>应返回一个字符串
- text: "<code>sentensify('May-the-force-be-with-you')</code>应返回一个字符串"
testString: assert(typeof sentensify("May-the-force-be-with-you") === "string");
- text: <code>sentensify(&quot;May-the-force-be-with-you&quot;)</code>应返回<code>&quot;May the force be with you&quot;</code>
- text: "<code>sentensify('May-the-force-be-with-you')</code>应返回<code>'May the force be with you'</code>。"
testString: assert(sentensify("May-the-force-be-with-you") === "May the force be with you");
- text: <code>sentensify(&quot;The.force.is.strong.with.this.one&quot;)</code>应返回<code>&quot;The force is strong with this one&quot;</code>
- text: "<code>sentensify('The.force.is.strong.with.this.one')</code>应返回<code>'The force is strong with this one'</code>。"
testString: assert(sentensify("The.force.is.strong.with.this.one") === "The force is strong with this one");
- text: '<code>sentensify(&quot;There,has,been,an,awakening&quot;)</code>应该回归<code>&quot;There has been an awakening&quot;</code> 。'
- text: "<code>sentensify('There,has,been,an,awakening')</code>应返回<code>'There has been an awakening'</code>。"
testString: assert(sentensify("There,has,been,an,awakening") === "There has been an awakening");
```
@ -47,7 +59,6 @@ function sentensify(str) {
// Add your code above this line
}
sentensify("May-the-force-be-with-you");
```
</div>
@ -60,6 +71,11 @@ sentensify("May-the-force-be-with-you");
<section id='solution'>
```js
// solution required
function sentensify(str) {
// Add your code below this line
return str.split(/\W/).join(' ');
// Add your code above this line
}
```
</section>

View File

@ -2,28 +2,38 @@
id: 587d7da9367417b2b2512b66
title: Combine Two Arrays Using the concat Method
challengeType: 1
videoUrl: ''
localeTitle: 使用concat方法组合两个数组
forumTopicId: 301229
localeTitle: 使用 concat 方法组合两个数组
---
## Description
<section id="description"> <code>Concatenation</code>意味着端到端地连接项目。 JavaScript为字符串和数组提供了以相同方式工作的<code>concat</code>方法。对于数组,该方法在一个上调用,然后另一个数组作为<code>concat</code>的参数提供,该数组被添加到第一个数组的末尾。它返回一个新数组,不会改变任何一个原始数组。这是一个例子: <blockquote> [1,2,3] .concat[4,5,6]; <br> //返回一个新数组[1,2,3,4,5,6] </blockquote></section>
<section id='description'>
<code>Concatenation</code>意思是将元素连接到尾部。同理JavaScript 为字符串和数组提供了<code>concat</code>方法。对数组来说,在一个数组上调用<code>concat</code>方法,然后提供另一个数组作为参数添加到第一个数组末尾,返回一个新数组,不会改变任何一个原始数组。举个例子:
```js
[1, 2, 3].concat([4, 5, 6]);
// 返回新数组 [1, 2, 3, 4, 5, 6]
```
</section>
## Instructions
<section id="instructions">使用<code>nonMutatingConcat</code>函数中的<code>concat</code>方法<code>attach</code><code>original</code>的结尾。该函数应返回连接数组。 </section>
<section id='instructions'>
<code>nonMutatingConcat</code>函数里使用<code>concat</code>,将<code>attach</code>拼接到<code>original</code>尾部,返回拼接后的数组。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 您的代码应使用<code>concat</code>方法。
- text: 使用<code>concat</code>方法。
testString: assert(code.match(/\.concat/g));
- text: <code>first</code>数组不应该改变
- text: 不能改变<code>first</code>数组。
testString: assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
- text: <code>second</code>数组不应该改变
- text: 不能改变<code>second</code>数组。
testString: assert(JSON.stringify(second) === JSON.stringify([4, 5]));
- text: '<code>nonMutatingConcat([1, 2, 3], [4, 5])</code>应返回<code>[1, 2, 3, 4, 5]</code> 。'
- text: <code>nonMutatingConcat([1, 2, 3], [4, 5])</code>应返回<code>[1, 2, 3, 4, 5]</code>
testString: assert(JSON.stringify(nonMutatingConcat([1, 2, 3], [4, 5])) === JSON.stringify([1, 2, 3, 4, 5]));
```
@ -45,7 +55,6 @@ function nonMutatingConcat(original, attach) {
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingConcat(first, second);
```
</div>
@ -58,6 +67,14 @@ nonMutatingConcat(first, second);
<section id='solution'>
```js
// solution required
function nonMutatingConcat(original, attach) {
// Add your code below this line
return original.concat(attach);
// Add your code above this line
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingConcat(first, second);
```
</section>

View File

@ -2,24 +2,31 @@
id: 587d7b8f367417b2b2512b62
title: Implement map on a Prototype
challengeType: 1
videoUrl: ''
localeTitle: 在Prototype上实现地图
forumTopicId: 301230
localeTitle: 在原型上实现 map 方法
---
## Description
<section id="description">正如您在应用<code>Array.prototype.map()</code>或之前简单地<code>map()</code>所看到的那样, <code>map</code>方法返回一个与调用它的长度相同的数组。它也不会改变原始数组,只要它的回调函数不会。换句话说, <code>map</code>是一个纯函数,它的输出完全取决于它的输入。另外,它需要另一个函数作为其参数。它会教我们很多关于<code>map</code>的尝试实现它的一个版本,它的行为与带有<code>for</code>循环或<code>Array.prototype.forEach()</code><code>Array.prototype.map()</code>完全相同。注意:允许纯函数改变在其范围内定义的局部变量,但是,最好也避免使用它。 </section>
<section id='description'>
我们之前用<code>map</code>方法(即<code>Array.prototype.map()</code>)返回一个与调用它的数组长度相同的数组。只要它的回调函数不改变原始数组,它就不会改变原始数组。
换句话说,<code>map</code>是一个纯函数,它的输出仅取决于输入的数组和作为参数传入的回调函数。
为了加深对<code>map</code>方法的理解,现在我们来用<code>for</code><code>Array.prototype.forEach()</code>自己实现一下这个方法。
注意:纯函数可以改变其作用域内定义的局部变量,但我们最好不要这样做。
</section>
## Instructions
<section id="instructions">编写自己的<code>Array.prototype.myMap()</code> ,其行为应与<code>Array.prototype.map()</code>完全相同。您可以使用<code>for</code>循环或<code>forEach</code>方法。 </section>
<section id='instructions'>
写一个和<code>Array.prototype.map()</code>一样的<code>Array.prototype.myMap()</code>。你可以用<code>for</code>循环或者<code>forEach</code>方法。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>new_s</code>应等于<code>[46, 130, 196, 10]</code> <code>new_s</code> <code>[46, 130, 196, 10]</code> 。'
- text: <code>new_s</code>应等于<code>[46, 130, 196, 10]</code>
testString: assert(JSON.stringify(new_s) === JSON.stringify([46, 130, 196, 10]));
- text: 您的代码不应使用<code>map</code>方法。
- text: 不能使用<code>map</code>方法。
testString: assert(!code.match(/\.map/g));
```
@ -47,7 +54,6 @@ Array.prototype.myMap = function(callback){
var new_s = s.myMap(function(item){
return item * 2;
});
```
</div>
@ -60,6 +66,23 @@ var new_s = s.myMap(function(item){
<section id='solution'>
```js
// solution required
// the global Array
var s = [23, 65, 98, 5];
Array.prototype.myMap = function(callback){
var newArray = [];
// Add your code below this line
for (var elem of this) {
newArray.push(callback(elem));
}
// Add your code above this line
return newArray;
};
var new_s = s.myMap(function(item){
return item * 2;
});
```
</section>

View File

@ -2,24 +2,29 @@
id: 587d7b8f367417b2b2512b64
title: Implement the filter Method on a Prototype
challengeType: 1
videoUrl: ''
localeTitle: 在Prototype上实现过滤器方法
forumTopicId: 301231
localeTitle: 在原型上实现 filter 方法
---
## Description
<section id="description">如果我们尝试实现与<code>Array.prototype.filter()</code>完全相同的版本,它会教会我们很多关于<code>filter</code>方法的内容。它可以使用<code>for</code>循环或<code>Array.prototype.forEach()</code> 。注意:允许纯函数改变在其范围内定义的局部变量,但是,最好也避免使用它。 </section>
<section id='description'>
为了加深对<code>filter</code>的理解,现在我们来自己实现一下<code>Array.prototype.filter()</code>方法。可以用<code>for</code>循环或<code>Array.prototype.forEach()</code>
请注意:纯函数可以改变其作用域内定义的局部变量,但我们最好不要这样做。
</section>
## Instructions
<section id="instructions">编写自己的<code>Array.prototype.myFilter()</code> ,其行为应与<code>Array.prototype.filter()</code>完全相同。您可以使用<code>for</code>循环或<code>Array.prototype.forEach()</code>方法。 </section>
<section id='instructions'>
编写一个和<code>Array.prototype.filter()</code>功能一样的<code>Array.prototype.myFilter()</code>方法。你可以用<code>for</code>循环或<code>Array.prototype.forEach()</code>方法。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>new_s</code>应等于<code>[23, 65, 5]</code> <code>new_s</code> <code>[23, 65, 5]</code> 。'
- text: <code>new_s</code>应等于<code>[23, 65, 5]</code>
testString: assert(JSON.stringify(new_s) === JSON.stringify([23, 65, 5]));
- text: 您的代码不应使用<code>filter</code>方法。
- text: 不能使用<code>filter</code>方法。
testString: assert(!code.match(/\.filter/g));
```
@ -47,7 +52,6 @@ Array.prototype.myFilter = function(callback){
var new_s = s.myFilter(function(item){
return item % 2 === 1;
});
```
</div>
@ -60,6 +64,23 @@ var new_s = s.myFilter(function(item){
<section id='solution'>
```js
// solution required
// the global Array
var s = [23, 65, 98, 5];
Array.prototype.myFilter = function(callback){
var newArray = [];
// Add your code below this line
for (let i = 0;i<this.length;i++) {
if (callback(this[i]))
newArray.push(this[i]);
}
// Add your code above this line
return newArray;
};
var new_s = s.myFilter(function(item){
return item % 2 === 1;
});
```
</section>

View File

@ -2,28 +2,73 @@
id: 587d7dab367417b2b2512b70
title: Introduction to Currying and Partial Application
challengeType: 1
videoUrl: ''
localeTitle: Currying和Partial Application简介
forumTopicId: 301232
localeTitle: 函数柯里化
---
## Description
<section id="description">函数的<code>arity</code>是它需要的参数数量。 <code>Currying</code>一个功能装置以n的函数转换<code>arity</code>为N的功能<code>arity</code> 1。换言之它重构的功能因此采用一个参数然后返回另一个函数它的下一个参数依此类推。这是一个例子 <blockquote> //非咖喱功能<br> function unCurriedxy{ <br>返回x + y; <br> } <br><br> // Curried功能<br> function curriedx{ <br> return函数y{ <br>返回x + y; <br> } <br> } <br> curried12//返回3 </blockquote>如果您无法一次为函数提​​供所有参数,则在程序中这很有用。您可以将每个函数调用保存到一个变量中,该变量将保存返回的函数引用,该引用在可用时接受下一个参数。以下是使用上面示例中的<code>curried</code>函数的示例: <blockquote> //在部分中调用curried函数 <br> var funcForY = curried1; <br>的console.logfuncForY2; //打印3 </blockquote>类似地, <code>partial application</code>可以描述为一次向函数应用一些参数并返回应用于更多参数的另一个函数。这是一个例子: <blockquote> //公正的功能<br>功能公正xyz{ <br> return x + y + z; <br> } <br> var partialFn = impartial.bindthis1,2; <br> partialFn10; //返回13 </blockquote></section>
<section id='description'>
<code>arity</code>是函数所需的形参的数量。函数<code>柯里化</code>意思是把接受多个<code>arity</code>的函数变换成接受单一<code>arity</code>的函数。
换句话说,就是重构函数让它接收一个参数,然后返回接收下一个参数的函数,依此类推。
举个例子:
```js
//Un-curried function
function unCurried(x, y) {
return x + y;
}
//柯里化函数
function curried(x) {
return function(y) {
return x + y;
}
}
//Alternative using ES6
const curried = x => y => x + y
curried(1)(2) // 返回 3
```
柯里化在不能一次为函数提供所有参数情况下很有用。因为它可以将每个函数的调用保存到一个变量中,该变量将保存返回的函数引用,该引用在下一个参数可用时接受该参数。下面是使用<code>柯里化</code>函数的例子:
```js
// Call a curried function in parts:
var funcForY = curried(1);
console.log(funcForY(2)); // Prints 3
```
类似地,<code>局部应用</code>的意思是一次对一个函数应用几个参数,然后返回另一个应用更多参数的函数。
举个例子:
```js
//Impartial function
function impartial(x, y, z) {
return x + y + z;
}
var partialFn = impartial.bind(this, 1, 2);
partialFn(10); // Returns 13
```
</section>
## Instructions
<section id="instructions">填写<code>add</code>函数的主体以便使用currying来添加参数<code>x</code> <code>y</code><code>z</code></section>
<section id='instructions'>
填写<code>add</code>函数主体部分,用柯里化添加参数<code>x</code><code>y</code><code>z</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>add(10)(20)(30)</code>应返回<code>60</code>
- text: <code>add(10)(20)(30)</code>应返回<code>60</code>。
testString: assert(add(10)(20)(30) === 60);
- text: <code>add(1)(2)(3)</code>应返回<code>6</code>
- text: <code>add(1)(2)(3)</code>应返回<code>6</code>。
testString: assert(add(1)(2)(3) === 6);
- text: <code>add(11)(22)(33)</code>应返回<code>66</code>
- text: <code>add(11)(22)(33)</code>应返回<code>66</code>。
testString: assert(add(11)(22)(33) === 66);
- text: 您的代码应包含返回<code>x + y + z</code>的final语句
- text: 返回<code>x + y + z</code>的最终结果
testString: assert(code.match(/[xyz]\s*?\+\s*?[xyz]\s*?\+\s*?[xyz]/g));
```
@ -43,7 +88,6 @@ function add(x) {
// Add your code above this line
}
add(10)(20)(30);
```
</div>
@ -56,6 +100,7 @@ add(10)(20)(30);
<section id='solution'>
```js
// solution required
const add = x => y => z => x + y + z
```
</section>

View File

@ -2,24 +2,34 @@
id: 587d7b8d367417b2b2512b5b
title: Learn About Functional Programming
challengeType: 1
videoUrl: ''
localeTitle: 了解功能编程
forumTopicId: 301233
localeTitle: 学习函数式编程
---
## Description
<section id="description">功能编程是一种编程风格,其中解决方案是简单,独立的功能,在功能范围之外没有任何副作用。 <code>INPUT -&gt; PROCESS -&gt; OUTPUT</code>功能编程是关于1隔离函数 - 不依赖于程序的状态其中包括可能发生变化的全局变量2纯函数 - 相同的输入总是给出相同的输出3副作用有限的功能 - 对功能外部程序状态的任何改变或突变都要仔细控制</section>
<section id='description'>
函数式编程是一种方案简单、功能独立、对作用域外没有任何副作用的编程范式。
<code>INPUT -> PROCESS -> OUTPUT</code>
函数式编程:
1功能独立——不依赖于程序的状态比如可能发生变化的全局变量
2纯函数——同一个输入永远能得到同一个输出
3有限的副作用——可以严格地限制函数外部对状态的更改。
</section>
## Instructions
<section id="instructions"> freeCodeCamp的成员碰巧爱茶。在代码编辑器中已经为您定义了<code>prepareTea</code><code>getTea</code>函数。调用<code>getTea</code>函数为团队获取40杯茶并将它们存储在<code>tea4TeamFCC</code>变量中。 </section>
<section id='instructions'>
freeCodeCamp 成员在 love tea 的故事。
在代码编辑器中,已经为你定义好了<code>prepareTea</code><code>getTea</code>函数。调用<code>getTea</code>函数为团队准备 40 杯茶,并将它们存储在<code>tea4TeamFCC</code>变量里。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>tea4TeamFCC</code>变量应该为团队提供40杯茶。
- text: <code>tea4TeamFCC</code>变量里应有 40 杯为团队准备的茶。
testString: assert(tea4TeamFCC.length === 40);
- text: <code>tea4TeamFCC</code>变量应该拿着一杯绿茶
- text: <code>tea4TeamFCC</code>变量里应有 greenTea
testString: assert(tea4TeamFCC[0] === 'greenTea');
```
@ -61,7 +71,6 @@ const tea4TeamFCC = null; // :(
// Add your code above this line
console.log(tea4TeamFCC);
```
</div>
@ -75,5 +84,20 @@ console.log(tea4TeamFCC);
```js
// solution required
const prepareTea = () => 'greenTea';
const getTea = (numOfCups) => {
const teaCups = [];
for(let cups = 1; cups <= numOfCups; cups += 1) {
const teaCup = prepareTea();
teaCups.push(teaCup);
}
return teaCups;
};
const tea4TeamFCC = getTea(40);
```
</section>

View File

@ -2,26 +2,36 @@
id: 587d7b8e367417b2b2512b5f
title: Pass Arguments to Avoid External Dependence in a Function
challengeType: 1
videoUrl: ''
forumTopicId: 301234
localeTitle: 传递参数以避免函数中的外部依赖
---
## Description
<section id="description">最后一个挑战是向功能编程原则迈进了一步,但仍然缺少一些东西。我们没有改变全局变量值,但是如果没有全局变量<code>fixedValue</code> ,函数<code>incrementer</code>将无法工作。函数式编程的另一个原则是始终明确声明您的依赖项。这意味着如果函数依赖于存在的变量或对象,则将该变量或对象作为参数直接传递给函数。这个原则有几个好的结果。该函数更容易测试,您确切知道它需要什么输入,并且它不依赖于程序中的任何其他内容。当您更改,删除或添加新代码时,这可以让您更有信心。你会知道你可以或不可以改变什么,你可以看到潜在陷阱的位置。最后,无论代码的哪一部分执行,函数总是会为同一组输入生成相同的输出。 </section>
<section id='description'>
上一个挑战是更接近函数式编程原则的挑战,但是仍然缺少一些东西。
虽然我们没有改变全局变量值,但在没有全局变量<code>fixedValue</code>情况下,<code>incrementer</code>函数将不起作用。
函数式编程的另一个原则是:总是显式声明依赖关系。如果函数依赖于一个变量或对象,那么将该变量或对象作为参数直接传递到函数中。
这样做会有很多好处,其中一点是让函数更容易测试,因为你确切地知道参数是什么,并且这个参数也不依赖于程序中的任何其他内容。
其次,这样做可以让你更加自信地更改,删除或添加新代码。因为你很清楚哪些是可以改的,哪些是不可以改的,这样你就知道哪里可能会有潜在的陷阱。
最后,无论代码的哪一部分执行它,函数总是会为同一组输入生成相同的输出。
</section>
## Instructions
<section id="instructions">让我们更新<code>incrementer</code>函数以清楚地声明其依赖关系。编写<code>incrementer</code>函数使其获取参数然后将值增加1。 </section>
<section id='instructions'>
更新<code>incrementer</code>函数,明确声明其依赖项。
编写<code>incrementer</code>函数,获取它的参数,然后将值增加 1。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 您的函数<code>incrementer</code>不应更改<code>fixedValue</code>的值。
- text: <code>incrementer</code>函数不能修改<code>fixedValue</code>的值。
testString: assert(fixedValue === 4);
- text: 您的<code>incrementer</code>功能应该采用参数。
- text: <code>incrementer</code>函数应该接收一个参数。
testString: assert(incrementer.length === 1);
- text: 您的<code>incrementer</code>函数应返回一个大于<code>fixedValue</code>的值。
- text: <code>incrementer</code>函数应返回<code>fixedValue</code>更大的值。
testString: assert(newValue === 5);
```
@ -46,7 +56,6 @@ function incrementer () {
var newValue = incrementer(fixedValue); // Should equal 5
console.log(fixedValue); // Should print 4
```
</div>
@ -59,6 +68,13 @@ console.log(fixedValue); // Should print 4
<section id='solution'>
```js
// solution required
// the global variable
var fixedValue = 4;
const incrementer = val => val + 1;
var newValue = incrementer(fixedValue); // Should equal 5
console.log(fixedValue); // Should print 4
```
</section>

View File

@ -2,28 +2,35 @@
id: 587d7b8f367417b2b2512b60
title: Refactor Global Variables Out of Functions
challengeType: 1
videoUrl: ''
localeTitle: 重构函数的全局变量
forumTopicId: 301235
localeTitle: 在函数中重构全局变量
---
## Description
<section id="description">到目前为止我们已经看到了函数式编程的两个不同原则1不要改变变量或对象 - 创建新的变量和对象,并在需要时从函数返回它们。 2声明函数参数 - 函数内的任何计算仅依赖于参数,而不依赖于任何全局对象或变量。在数字中添加一个并不是很令人兴奋,但我们可以在处理数组或更复杂的对象时应用这些原则。 </section>
<section id='description'>
目前为止,我们已经看到了函数式编程的两个原则:
1) 不要更改变量或对象——创建新变量和对象,并在需要时从函数返回它们。
2) 声明函数参数——函数内的任何计算仅取决于参数,而不取决于任何全局对象或变量。
给数字增加 1 不够刺激,我们可以在处理数组或更复杂的对象时应用这些原则。
</section>
## Instructions
<section id="instructions">重构(重写)代码,以便在任一函数内部不更改全局数组<code>bookList</code><code>add</code>函数应该将给定的<code>bookName</code>添加到数组的末尾。 <code>remove</code>函数应该从数组中删除给定的<code>bookName</code> 。这两个函数都应该返回一个数组,并且应该在<code>bookName</code>之前添加任何新参数。 </section>
<section id='instructions'>
重构代码,使全局数组<code>bookList</code>在函数内部不会被改变。<code>add</code>函数可以将指定的<code>bookName</code>增加到数组末尾。<code>remove</code>函数可以从数组中移除指定<code>bookName</code>。两个函数都返回数组,并且任何参数都应该添加到<code>bookName</code>前面。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>bookList</code>不应该改变并且仍然相等<code>[&quot;The Hound of the Baskervilles&quot;, &quot;On The Electrodynamics of Moving Bodies&quot;, &quot;Philosophiæ Naturalis Principia Mathematica&quot;, &quot;Disquisitiones Arithmeticae&quot;]</code> 。'
- text: "<code>bookList</code>不应该改变,应等于<code>['The Hound of the Baskervilles', 'On The Electrodynamics of Moving Bodies', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae']</code>."
testString: assert(JSON.stringify(bookList) === JSON.stringify(["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]));
- text: '<code>newBookList</code>应等于<code>[&quot;The Hound of the Baskervilles&quot;, &quot;On The Electrodynamics of Moving Bodies&quot;, &quot;Philosophiæ Naturalis Principia Mathematica&quot;, &quot;Disquisitiones Arithmeticae&quot;, &quot;A Brief History of Time&quot;]</code> 。'
- text: "<code>newBookList</code>应等于<code>['The Hound of the Baskervilles', 'On The Electrodynamics of Moving Bodies', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae', 'A Brief History of Time']</code>."
testString: assert(JSON.stringify(newBookList) === JSON.stringify(['The Hound of the Baskervilles', 'On The Electrodynamics of Moving Bodies', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae', 'A Brief History of Time']));
- text: '<code>newerBookList</code>应等于<code>[&quot;The Hound of the Baskervilles&quot;, &quot;Philosophiæ Naturalis Principia Mathematica&quot;, &quot;Disquisitiones Arithmeticae&quot;]</code> 。'
- text: "<code>newerBookList</code>应等于<code>['The Hound of the Baskervilles', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae']</code>."
testString: assert(JSON.stringify(newerBookList) === JSON.stringify(['The Hound of the Baskervilles', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae']));
- text: '<code>newestBookList</code>应等于<code>[&quot;The Hound of the Baskervilles&quot;, &quot;Philosophiæ Naturalis Principia Mathematica&quot;, &quot;Disquisitiones Arithmeticae&quot;, &quot;A Brief History of Time&quot;]</code> 。'
- text: "<code>newestBookList</code>应等于<code>['The Hound of the Baskervilles', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae', 'A Brief History of Time']</code>."
testString: assert(JSON.stringify(newestBookList) === JSON.stringify(['The Hound of the Baskervilles', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae', 'A Brief History of Time']));
```
@ -40,13 +47,14 @@ tests:
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
/* This function should add a book to the list and return the list */
// New parameters should come before the bookName one
// New parameters should come before bookName
// Add your code below this line
function add (bookName) {
return bookList.push(bookName);
bookList.push(bookName);
return bookList;
// Add your code above this line
}
@ -55,9 +63,11 @@ function add (bookName) {
// Add your code below this line
function remove (bookName) {
if (bookList.indexOf(bookName) >= 0) {
var book_index = bookList.indexOf(bookName);
if (book_index >= 0) {
return bookList.splice(0, 1, bookName);
bookList.splice(book_index, 1);
return bookList;
// Add your code above this line
}
@ -68,7 +78,6 @@ var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
console.log(bookList);
```
</div>
@ -81,6 +90,35 @@ console.log(bookList);
<section id='solution'>
```js
// solution required
// the global variable
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
/* This function should add a book to the list and return the list */
// New parameters should come before the bookName one
// Add your code below this line
function add (bookList, bookName) {
return [...bookList, bookName];
// Add your code above this line
}
/* This function should remove a book from the list and return the list */
// New parameters should come before the bookName one
// Add your code below this line
function remove (bookList, bookName) {
const bookListCopy = [...bookList];
const bookNameIndex = bookList.indexOf(bookName);
if (bookNameIndex >= 0) {
bookListCopy.splice(bookNameIndex, 1);
}
return bookListCopy;
// Add your code above this line
}
var newBookList = add(bookList, 'A Brief History of Time');
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
```
</section>

View File

@ -2,28 +2,41 @@
id: 9d7123c8c441eeafaeb5bdef
title: Remove Elements from an Array Using slice Instead of splice
challengeType: 1
videoUrl: ''
localeTitle: 使用切片从阵列中删除元素而不是拼接
forumTopicId: 301236
localeTitle: 使用 slice 而不是 splice 从数组中移除元素
---
## Description
<section id="description">使用数组时的常见模式是当您想要删除项目并保留数组的其余部分时。 JavaScript为此提供了<code>splice</code>方法,该方法接受索引的参数,该索引指示从何处开始删除项目,然后是要删除的项目数。如果未提供第二个参数,则默认为通过结尾删除项目。但是, <code>splice</code>方法会改变调用它的原始数组。这是一个例子: <blockquote> var cities = [“芝加哥”,“德里”,“伊斯兰堡”,“伦敦”,“柏林”]; <br> cities.splice3,1; //返回“London”并从cities数组中删除它<br> //现在是城市[“芝加哥”,“德里”,“伊斯兰堡”,“柏林”] </blockquote>正如我们在上一次挑战中看到的那样, <code>slice</code>方法不会改变原始数组,而是返回一个可以保存到变量中的新数组。回想一下, <code>slice</code>方法为索引开始和结束<code>slice</code>采用两个参数(结束是非包含的),并在新数组中返回这些项。使用<code>slice</code>方法而不是<code>splice</code>有助于避免任何阵列变异的副作用。 </section>
<section id='description'>
使用数组时经常遇到要删除一些元素并保留数组剩余部分的情况。为此JavaScript 提供了<code>splice</code>方法,它接收两个参数:从哪里开始删除项目的索引,和要删除的项目数。如果没有提供第二个参数,默认情况下是移除到结尾的元素。但<code>splice</code>方法会改变调用它的原始数组。举个例子:
```js
var cities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
cities.splice(3, 1); // Returns "London" and deletes it from the cities array
// cities is now ["Chicago", "Delhi", "Islamabad", "Berlin"]
```
正如我们在上一次挑战中看到的那样,<code>slice</code>方法不会改变原始数组,而是返回一个可以保存到变量中的新数组。回想一下,<code>slice</code>方法接收两个参数,从开始索引开始选取到结束(不包括该元素),并在新数组中返回这些元素。使用<code>slice</code>方法替代<code>splice</code>有助于避免数组变化产生的副作用。
</section>
## Instructions
<section id="instructions">使用<code>slice</code>而不是<code>splice</code>重写函数<code>nonMutatingSplice</code> 。它应该将提供的<code>cities</code>数组限制为3的长度并返回仅包含前三项的新数组。不要改变提供给函数的原始数组。 </section>
<section id='instructions'>
<code>slice</code>代替<code>splice</code>重写<code>nonMutatingSplice</code>函数。将<code>cities</code>数组长度限制为3并返回一个仅包含前 3 项的新数组。
不要改变提供给函数的原始数组。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 您的代码应该使用<code>slice</code>方法。
- text: 应该使用<code>slice</code>方法。
testString: assert(code.match(/\.slice/g));
- text: 您的代码不应使用<code>splice</code>方法。
- text: 不能使用<code>splice</code>方法。
testString: assert(!code.match(/\.splice/g));
- text: <code>inputCities</code>数组不应更改
- text: 不能改变<code>inputCities</code>数组。
testString: assert(JSON.stringify(inputCities) === JSON.stringify(["Chicago", "Delhi", "Islamabad", "London", "Berlin"]));
- text: '<code>nonMutatingSplice([&quot;Chicago&quot;, &quot;Delhi&quot;, &quot;Islamabad&quot;, &quot;London&quot;, &quot;Berlin&quot;])</code>应返回<code>[&quot;Chicago&quot;, &quot;Delhi&quot;, &quot;Islamabad&quot;]</code> 。'
- text: "<code>nonMutatingSplice(['Chicago', 'Delhi', 'Islamabad', 'London', 'Berlin'])</code>应返回<code>['Chicago', 'Delhi', 'Islamabad']</code>。"
testString: assert(JSON.stringify(nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])) === JSON.stringify(["Chicago", "Delhi", "Islamabad"]));
```
@ -44,7 +57,6 @@ function nonMutatingSplice(cities) {
}
var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
nonMutatingSplice(inputCities);
```
</div>
@ -57,6 +69,13 @@ nonMutatingSplice(inputCities);
<section id='solution'>
```js
// solution required
function nonMutatingSplice(cities) {
// Add your code below this line
return cities.slice(0,3);
// Add your code above this line
}
var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
nonMutatingSplice(inputCities);
```
</section>

View File

@ -2,28 +2,32 @@
id: 587d7da9367417b2b2512b6a
title: Return a Sorted Array Without Changing the Original Array
challengeType: 1
videoUrl: ''
localeTitle: 返回排序数组而不更改原始数组
forumTopicId: 301237
localeTitle: 在不更改原始数组的前提下返回排序后的数组
---
## Description
<section id="description"> <code>sort</code>方法的一个副作用是它改变了原始数组中元素的顺序。换句话说,它将阵列变异。避免这种情况的一种方法是首先将空数组连接到正在排序的数组(记住<code>concat</code>返回一个新数组),然后运行<code>sort</code>方法。 </section>
<section id='description'>
<code>sort</code>方法会产生改变原始数组中元素顺序的副作用。换句话说,它会改变数组的位置。避免这种情况的一种方法是先将空数组连接到正在排序的数组上(记住<code>concat</code>返回一个新数组),再用<code>sort</code>方法。
</section>
## Instructions
<section id="instructions">使用<code>nonMutatingSort</code>函数中的<code>sort</code>方法按升序对数组元素进行排序。该函数应该返回一个新数组,而不是改变<code>globalArray</code>变量。 </section>
<section id='instructions'>
<code>nonMutatingSort</code>函数中使用<code>sort</code>方法对数组中的元素按升序进行排列。函数不能改变<code>globalArray</code>变量,应返回一个新数组。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 您的代码应该使用<code>sort</code>方法。
- text: 应该使用<code>sort</code>方法。
testString: assert(nonMutatingSort.toString().match(/\.sort/g));
- text: 您的代码应使用<code>concat</code>方法。
- text: 使用<code>concat</code>方法。
testString: assert(JSON.stringify(globalArray) === JSON.stringify([5, 6, 3, 2, 9]));
- text: <code>globalArray</code>变量不应该更改
- text: <code>globalArray</code>variable 应保持不变
testString: assert(JSON.stringify(nonMutatingSort(globalArray)) === JSON.stringify([2, 3, 5, 6, 9]));
- text: '<code>nonMutatingSort(globalArray)</code>应返回<code>[2, 3, 5, 6, 9]</code> <code>nonMutatingSort(globalArray)</code> <code>[2, 3, 5, 6, 9]</code> 。'
- text: <code>nonMutatingSort(globalArray)</code>应返回<code>[2, 3, 5, 6, 9]</code>
testString: assert(!nonMutatingSort.toString().match(/[23569]/g));
```
@ -44,7 +48,6 @@ function nonMutatingSort(arr) {
// Add your code above this line
}
nonMutatingSort(globalArray);
```
</div>
@ -57,6 +60,13 @@ nonMutatingSort(globalArray);
<section id='solution'>
```js
// solution required
var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
// Add your code below this line
return [].concat(arr).sort((a,b) => a-b);
// Add your code above this line
}
nonMutatingSort(globalArray);
```
</section>

View File

@ -2,30 +2,42 @@
id: 587d7b90367417b2b2512b65
title: Return Part of an Array Using the slice Method
challengeType: 1
videoUrl: ''
localeTitle: 使用切片方法返回数组的一部分
forumTopicId: 301239
localeTitle: 使用 slice 方法返回数组的一部分
---
## Description
<section id="description"> <code>slice</code>方法返回数组的某些元素的副本。它可以采用两个参数,第一个给出切片开始位置的索引,第二个是切片结束位置的索引(并且它是非包含的)。如果未提供参数,则默认为从数组的开头到结尾开始,这是复制整个数组的简单方法。 <code>slice</code>方法不会改变原始数组,但会返回一个新数组。这是一个例子: <blockquote> var arr = [“Cat”“Dog”“Tiger”“Zebra”]; <br> var newArray = arr.slice1,3; <br> //将newArray设置为[“Dog”“Tiger”] </blockquote></section>
<section id='description'>
<code>slice</code>方法可以从已有数组中返回指定元素。它接受两个参数,第一个规定从何处开始选取,第二个规定从何处结束选取(不包括该元素)。如果没有传参,则默认为从数组的开头开始到结尾结束,这是复制整个数组的简单方式。<code>slice</code>返回一个新数组,不会修改原始数组。
举个例子:
```js
var arr = ["Cat", "Dog", "Tiger", "Zebra"];
var newArray = arr.slice(1, 3);
// Sets newArray to ["Dog", "Tiger"]
```
</section>
## Instructions
<section id="instructions">在给定提供的<code>beginSlice</code><code>endSlice</code>索引的情况下,使用<code>sliceArray</code>函数中的<code>slice</code>方法返回<code>anim</code>数组的一部分。该函数应返回一个数组。 </section>
<section id='instructions'>
<code>sliceArray</code>函数中使用<code>slice</code>方法,给出<code>beginSlice</code><code>endSlice</code>索引,返回<code>anim</code>数组的一部分,这个函数应返回一个数组。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 的代码应使用<code>slice</code>方法。
- text: 的代码应使用<code>slice</code>方法。
testString: assert(code.match(/\.slice/g));
- text: <code>inputAnim</code>变量不应该更改
- text: 不能改变<code>inputAnim</code>变量。
testString: assert(JSON.stringify(inputAnim) === JSON.stringify(["Cat", "Dog", "Tiger", "Zebra", "Ant"]));
- text: '<code>sliceArray([&quot;Cat&quot;, &quot;Dog&quot;, &quot;Tiger&quot;, &quot;Zebra&quot;, &quot;Ant&quot;], 1, 3)</code>应返回<code>[&quot;Dog&quot;, &quot;Tiger&quot;]</code> 。'
- text: "<code>sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 1, 3)</code>应返回<code>['Dog', 'Tiger']</code>。"
testString: assert(JSON.stringify(sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3)) === JSON.stringify(["Dog", "Tiger"]));
- text: '<code>sliceArray([&quot;Cat&quot;, &quot;Dog&quot;, &quot;Tiger&quot;, &quot;Zebra&quot;, &quot;Ant&quot;], 0, 1)</code>应返回<code>[&quot;Cat&quot;]</code> 。'
- text: "<code>sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 0, 1)</code>应返回<code>['Cat']</code>。"
testString: assert(JSON.stringify(sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1)) === JSON.stringify(["Cat"]));
- text: '<code>sliceArray([&quot;Cat&quot;, &quot;Dog&quot;, &quot;Tiger&quot;, &quot;Zebra&quot;, &quot;Ant&quot;], 1, 4)</code>应返回<code>[&quot;Dog&quot;, &quot;Tiger&quot;, &quot;Zebra&quot;]</code> 。'
- text: "<code>sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 1, 4)</code>应返回<code>['Dog', 'Tiger', 'Zebra']</code>。"
testString: assert(JSON.stringify(sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4)) === JSON.stringify(["Dog", "Tiger", "Zebra"]));
```
@ -46,7 +58,6 @@ function sliceArray(anim, beginSlice, endSlice) {
}
var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
sliceArray(inputAnim, 1, 3);
```
</div>
@ -59,6 +70,13 @@ sliceArray(inputAnim, 1, 3);
<section id='solution'>
```js
// solution required
function sliceArray(anim, beginSlice, endSlice) {
// Add your code below this line
return anim.slice(beginSlice, endSlice)
// Add your code above this line
}
var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
sliceArray(inputAnim, 1, 3);
```
</section>

View File

@ -2,28 +2,57 @@
id: 587d7da9367417b2b2512b69
title: Sort an Array Alphabetically using the sort Method
challengeType: 1
videoUrl: ''
localeTitle: 使用sort方法按字母顺序数组进行排序
forumTopicId: 18303
localeTitle: 使用 sort 方法按字母顺序数组排序
---
## Description
<section id="description"> <code>sort</code>方法根据回调函数对数组的元素进行<code>sort</code> 。例如: <blockquote> function ascendingOrderarr{ <br> return arr.sortfunctionab{ <br>返回a - b; <br> }; <br> } <br> ascendingOrder[1,5,2,3,4]; <br> //返回[1,2,3,4,5] <br><br> function reverseAlphaarr{ <br> return arr.sortfunctionab{ <br>返回&lt;b; <br> }; <br> } <br> reverseAlpha[&#39;l&#39;&#39;h&#39;&#39;z&#39;&#39;b&#39;&#39;s&#39;]; <br> //返回[&#39;z&#39;&#39;s&#39;&#39;l&#39;&#39;h&#39;&#39;b&#39;] </blockquote>注意:鼓励提供回调函数来指定如何对数组项进行排序。 JavaScript的默认排序方法是字符串Unicode点值这可能会返回意外结果。 </section>
<section id='description'>
<code>sort</code>方法可以根据回调函数对数组元素进行排序。
举个例子:
```js
function ascendingOrder(arr) {
return arr.sort(function(a, b) {
return a - b;
});
}
ascendingOrder([1, 5, 2, 3, 4]);
// Returns [1, 2, 3, 4, 5]
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 的默认排序方法是 Unicode 值顺序排序,有时可能会得到意想不到的结果。所以,建议传入一个回调函数指定数组项目的排序方式,这个回调函数通常叫做 <code>compareFunction</code>,它根据 <code>compareFunction</code> 的返回值决定数组元素的排序方式:
如果两个元素 <code>a</code><code>b</code><code>compareFunction(a,b)</code> 返回一个比 0 小的值,那么 <code>a</code> 会在 <code>b</code> 的前面。
如果两个元素 <code>a</code><code>b</code><code>compareFunction(a,b)</code> 返回一个比 0 大的值,那么 <code>b</code> 会在 <code>a</code> 的前面。
如果两个元素 <code>a</code><code>b</code><code>compareFunction(a,b)</code> 返回等于 0 的值,那么 <code>a</code><code>b</code> 的位置保持不变。
</section>
## Instructions
<section id="instructions">使用<code>alphabeticalOrder</code>函数中的<code>sort</code>方法<code>alphabeticalOrder</code>字母顺序对<code>arr</code>的元素进行排序。 </section>
<section id='instructions'>
<code>alphabeticalOrder</code>函数中使用<code>sort</code>方法对<code>arr</code>中的元素按照字母顺序排列。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 您的代码应该使用<code>sort</code>方法。
- text: 应该使用<code>sort</code>方法。
testString: assert(code.match(/\.sort/g));
- text: '<code>alphabeticalOrder([&quot;a&quot;, &quot;d&quot;, &quot;c&quot;, &quot;a&quot;, &quot;z&quot;, &quot;g&quot;])</code>应返回<code>[&quot;a&quot;, &quot;a&quot;, &quot;c&quot;, &quot;d&quot;, &quot;g&quot;, &quot;z&quot;]</code> 。'
- text: "<code>alphabeticalOrder(['a', 'd', 'c', 'a', 'z', 'g'])</code>应返回<code>['a', 'a', 'c', 'd', 'g', 'z']</code>。"
testString: assert(JSON.stringify(alphabeticalOrder(["a", "d", "c", "a", "z", "g"])) === JSON.stringify(["a", "a", "c", "d", "g", "z"]));
- text: '<code>alphabeticalOrder([&quot;x&quot;, &quot;h&quot;, &quot;a&quot;, &quot;m&quot;, &quot;n&quot;, &quot;m&quot;])</code>应返回<code>[&quot;a&quot;, &quot;h&quot;, &quot;m&quot;, &quot;m&quot;, &quot;n&quot;, &quot;x&quot;]</code> 。'
- text: "<code>alphabeticalOrder(['x', 'h', 'a', 'm', 'n', 'm'])</code>应返回<code>['a', 'h', 'm', 'm', 'n', 'x']</code>。"
testString: assert(JSON.stringify(alphabeticalOrder(["x", "h", "a", "m", "n", "m"])) === JSON.stringify(["a", "h", "m", "m", "n", "x"]));
- text: '<code>alphabeticalOrder([&quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;x&quot;, &quot;t&quot;])</code>应返回<code>[&quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;t&quot;, &quot;x&quot;]</code> 。'
- text: "<code>alphabeticalOrder(['a', 'a', 'a', 'a', 'x', 't'])</code>应返回<code>['a', 'a', 'a', 'a', 't', 'x']</code>。"
testString: assert(JSON.stringify(alphabeticalOrder(["a", "a", "a", "a", "x", "t"])) === JSON.stringify(["a", "a", "a", "a", "t", "x"]));
```
@ -43,7 +72,6 @@ function alphabeticalOrder(arr) {
// Add your code above this line
}
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
```
</div>
@ -56,6 +84,12 @@ alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
<section id='solution'>
```js
// solution required
function alphabeticalOrder(arr) {
// Add your code below this line
return arr.sort();
// Add your code above this line
}
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
```
</section>

View File

@ -2,28 +2,45 @@
id: 587d7daa367417b2b2512b6b
title: Split a String into an Array Using the split Method
challengeType: 1
videoUrl: ''
localeTitle: 使用split方法将字符串拆分数组
forumTopicId: 18305
localeTitle: 使用 split 方法将字符串拆分数组
---
## Description
<section id="description"> <code>split</code>方法将字符串拆分为字符串数组。它接受分隔符的参数,分隔符可以是用于分解字符串或正则表达式的字符。例如,如果分隔符是空格,则会得到一个单词数组,如果分隔符是空字符串,则会得到字符串中每个字符的数组。下面是两个用空格分隔一个字符串的例子,然后用正则表达式用数字分割另一个字符串: <blockquote> var str =“Hello World”; <br> var bySpace = str.split“”; <br> //将bySpace设置为[“Hello”“World”] <br><br> var otherString =“How9are7you2today”; <br> var byDigits = otherString.split/ \ d /; <br> //将byDigits设置为[“How”“are”“you”“today”] </blockquote>由于字符串是不可变的,因此<code>split</code>方法可以更轻松地使用它们。 </section>
<section id='description'>
<code>split</code>方法用于把字符串分割成字符串数组,接收一个分隔符参数,分隔符可以是用于分解字符串或正则表达式的字符。举个例子,如果分隔符是空格,你会得到一个单词数组;如果分隔符是空字符串,你会得到一个由字符串中每个字符组成的数组。
下面是两个用空格分隔一个字符串的例子,另一个是用数字的正则表达式分隔:
```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"]
```
因为字符串是固定的,<code>split</code>方法可以更简单的操作它们。
</section>
## Instructions
<section id="instructions">使用<code>splitify</code>函数内的<code>split</code>方法将<code>str</code>拆分为单词数组。该函数应该返回数组。请注意,单词并不总是用空格分隔,并且数组不应包含标点符号。 </section>
<section id='instructions'>
<code>splitify</code>函数中用<code>split</code>方法将<code>str</code>分割成单词数组,这个方法应该返回一个数组。单词不一定都是用空格分隔,所以数组中不应包含标点符号。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 您的代码应该使用<code>split</code>方法。
- text: 应该使用<code>split</code>方法。
testString: assert(code.match(/\.split/g));
- text: '<code>splitify(&quot;Hello World,I-am code&quot;)</code>应返回<code>[&quot;Hello&quot;, &quot;World&quot;, &quot;I&quot;, &quot;am&quot;, &quot;code&quot;]</code> 。'
- text: "<code>splitify('Hello World,I-am code')</code>应返回<code>['Hello', 'World', 'I', 'am', 'code']</code>。"
testString: assert(JSON.stringify(splitify("Hello World,I-am code")) === JSON.stringify(["Hello", "World", "I", "am", "code"]));
- text: '<code>splitify(&quot;Earth-is-our home&quot;)</code>应返回<code>[&quot;Earth&quot;, &quot;is&quot;, &quot;our&quot;, &quot;home&quot;]</code> 。'
- text: "<code>splitify('Earth-is-our home')</code>应返回<code>['Earth', 'is', 'our', 'home']</code>。"
testString: assert(JSON.stringify(splitify("Earth-is-our home")) === JSON.stringify(["Earth", "is", "our", "home"]));
- text: '<code>splitify(&quot;This.is.a-sentence&quot;)</code>应返回<code>[&quot;This&quot;, &quot;is&quot;, &quot;a&quot;, &quot;sentence&quot;]</code> 。'
- text: "<code>splitify('This.is.a-sentence')</code>应返回<code>['This', 'is', 'a', 'sentence']</code>。"
testString: assert(JSON.stringify(splitify("This.is.a-sentence")) === JSON.stringify(["This", "is", "a", "sentence"]));
```
@ -43,7 +60,6 @@ function splitify(str) {
// Add your code above this line
}
splitify("Hello World,I-am code");
```
</div>
@ -56,6 +72,11 @@ splitify("Hello World,I-am code");
<section id='solution'>
```js
// solution required
function splitify(str) {
// Add your code below this line
return str.split(/\W/);
// Add your code above this line
}
```
</section>

View File

@ -2,28 +2,39 @@
id: 587d7b8e367417b2b2512b5c
title: Understand Functional Programming Terminology
challengeType: 1
videoUrl: ''
localeTitle: 理解功能编程术语
forumTopicId: 301240
localeTitle: 了解函数式编程术语
---
## Description
<section id="description">联邦通信委员会团队有一种情绪波动,现在想要两种类型的茶:绿茶和红茶。一般事实:客户情绪波动很常见。有了这些信息,我们需要重新审视上次挑战中的<code>getTea</code>功能,以处理各种茶叶请求。我们可以修改<code>getTea</code>来接受一个函数作为参数,以便能够改变它准备的茶的类型。这使得<code>getTea</code>更加灵活,并且在客户端请求发生变化时为程序员提供更多控制。但首先,让我们介绍一些函数术语: <code>Callbacks</code>函数是滑动或传递给另一个函数来决定函数调用的函数。您可能已经看到它们传递给其他方法,例如在<code>filter</code> 回调函数告诉JavaScript如何过滤数组的标准。可以分配给变量传递到另一个函数或从其他函数返回的函数就像任何其他正常值一样称为<code>first class</code>函数。在JavaScript中所有函数都是<code>first class</code>函数。将函数作为参数或将函数作为返回值返回的函数称为<code>higher order</code>函数。当函数传递给另一个函数或从另一个函数返回时,那些传入或返回的函数可以称为<code>lambda</code></section>
<section id='description'>
FCC 团队需求有变更现在想要两种茶绿茶green tea和红茶black tea。事实证明用户需求变更是很常见的。
基于以上信息,我们需要重构上一节挑战中的<code>getTea</code>函数来处理多种茶的请求。我们可以修改<code>getTea</code>接受一个函数作为参数,使它能够修改茶的类型。这让<code>getTea</code>更灵活,也使需求变更时为程序员提供更多控制权。
首先,我们将介绍一些术语:
<code>Callbacks</code>是被传递到另一个函数中调用的函数。你应该已经在其他函数中看过这个写法,例如在<code>filter</code>中,回调函数告诉 JavaScript 以什么规则过滤数组。
函数就像其他正常值一样,可以赋值给变量、传递给另一个函数,或从其它函数返回,这种函数叫做<code>头等</code>函数。在 JavaScript 中,所有函数都是<code>头等</code>函数。
将函数为参数或返回值的函数叫做<code>高阶</code>函数。
当函数传递给另一个函数或从另一个函数返回时,那些传入或返回的函数可以叫做<code>lambda</code>
</section>
## Instructions
<section id="instructions">准备27杯绿茶和13杯红茶分别储存在<code>tea4GreenTeamFCC</code><code>tea4BlackTeamFCC</code>变量中。请注意, <code>getTea</code>函数已被修改,因此它现在将函数作为第一个参数。注意:数据(茶杯数量)作为最后一个参数提供。我们将在后面的课程中对此进行更多讨论。 </section>
<section id='instructions'>
准备 27 杯绿茶和 13 杯红茶,分别存入<code>tea4GreenTeamFCC</code><code>tea4BlackTeamFCC</code>变量。请注意,<code>getTea</code>函数已经变了,现在它接收一个函数作为第一个参数。
注意:数据(茶的数量)作为最后一个参数。我们将在后面的课程中对此进行更多讨论。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>tea4GreenTeamFCC</code>变量应为团队提供27杯绿茶。
- text: <code>tea4GreenTeamFCC</code>变量应存有为团队准备的 27 杯茶。
testString: assert(tea4GreenTeamFCC.length === 27);
- text: <code>tea4GreenTeamFCC</code>变量应该拿着一杯绿茶。
- text: <code>tea4GreenTeamFCC</code>变量应存有绿茶。
testString: assert(tea4GreenTeamFCC[0] === 'greenTea');
- text: <code>tea4BlackTeamFCC</code>变量应该可以容纳13杯红茶。
- text: <code>tea4BlackTeamFCC</code>变量应存有 13 杯红茶。
testString: assert(tea4BlackTeamFCC.length === 13);
- text: <code>tea4BlackTeamFCC</code>变量应该拿着一杯红茶。
- text: <code>tea4BlackTeamFCC</code>变量应存有红茶。
testString: assert(tea4BlackTeamFCC[0] === 'blackTea');
```
@ -76,7 +87,6 @@ console.log(
tea4GreenTeamFCC,
tea4BlackTeamFCC
);
```
</div>
@ -90,5 +100,21 @@ console.log(
```js
// solution required
const prepareGreenTea = () => 'greenTea';
const prepareBlackTea = () => 'blackTea';
const getTea = (prepareTea, numOfCups) => {
const teaCups = [];
for(let cups = 1; cups <= numOfCups; cups += 1) {
const teaCup = prepareTea();
teaCups.push(teaCup);
}
return teaCups;
};
const tea4BlackTeamFCC = getTea(prepareBlackTea, 13);
const tea4GreenTeamFCC = getTea(prepareGreenTea, 27);
```
</section>

View File

@ -2,15 +2,30 @@
id: 587d7b8e367417b2b2512b5d
title: Understand the Hazards of Using Imperative Code
challengeType: 1
videoUrl: ''
localeTitle: 了解使用命令代码的危害
forumTopicId: 301241
localeTitle: 了解使用命令式编程的危害
---
## Description
<section id="description">功能编程是一个好习惯。它使您的代码易于管理,并使您免于偷偷摸摸的错误。但在我们到达那里之前,让我们看一下编程的必要方法,以突出您可能遇到的问题。在英语(和许多其他语言)中,命令式时态用于给出命令。类似地,编程中的命令式是为计算机提供一组语句来执行任务。通常,语句会更改程序的状态,例如更新全局变量。一个典型的例子是编写一个<code>for</code>循环,它给出了迭代数组索引的精确方向。相反,函数式编程是声明式编程的一种形式。通过调用方法或函数告诉计算机您想要做什么。 JavaScript提供了许多处理常见任务的预定义方法因此您无需写出计算机应如何执行它们。例如您可以调用<code>map</code>方法来处理迭代数组的细节,而不是使用上面提到的<code>for</code>循环。这有助于避免语义错误例如调试部分中介绍的“Off By One Errors”。请考虑以下情况您正在浏览器中浏览Web并希望跟踪已打开的选项卡。让我们尝试使用一些简单的面向对象的代码对此进行建模。 Window对象由选项卡组成您通常打开多个Window。每个Window对象中每个开放站点的标题都保存在一个数组中。在浏览器中工作打开新选项卡合并窗口和关闭选项卡您需要打印仍处于打开状态的选项卡。从数组中删除已关闭的选项卡并将新选项卡为简单起见添加到其末尾。代码编辑器显示了此功能的实现其中包含<code>tabOpen()</code> <code>tabClose()</code><code>join()</code>函数。数组<code>tabs</code>是Window对象的一部分用于存储打开页面的名称。 <h4>说明</h4><h4>在编辑器中运行代码。它使用的方法在程序中有副作用,导致输出错误。打开标签的最终列表应该是<code>[&#39;FB&#39;, &#39;Gitter&#39;, &#39;Reddit&#39;, &#39;Twitter&#39;, &#39;Medium&#39;, &#39;new tab&#39;, &#39;Netflix&#39;, &#39;YouTube&#39;, &#39;Vine&#39;, &#39;GMail&#39;, &#39;Work mail&#39;, &#39;Docs&#39;, &#39;freeCodeCamp&#39;, &#39;new tab&#39;]</code>但输出会略有不同。完成代码并查看是否可以找出问题,然后进入下一个挑战以了解更多信息。 </h4></section>
<section id='description'>
函数式编程是一种好习惯,它能让代码管理更简单,不受隐藏 bug 影响。在我们开始函数式编程之前,为了更好的突显可能遇到的问题,我们先看看命令式编程。
类似在英语(和许多其他语言)中,命令式时态用于给出命令,编程中的命令式是给计算机一组语句来执行任务。
这些语句通常会改变程序的状态,例如更新全局变量,典型的例子就是写一个 <code>for</code> 循环,它给出了迭代数组索引的精确方向。
相反,函数式编程是声明式编程的一种形式,通过调用方法或函数来告诉计算机要做什么。
JavaScript 提供了许多处理常见任务的方法,所以你无需写出计算机应如何执行它们。例如,你可以用 <code>map</code> 函数替代上面提到的 <code>for</code> 循环来处理数组迭代。这有助于避免语义错误,如调试章节介绍的"Off By One Errors"。
考虑这样的场景:你正在浏览器中浏览网页,并想操作你打开的标签。下面我们来试试用面向对象的思路来描述这种情景。
窗口对象由选项卡组成,通常会打开多个窗口。窗口对象中每个打开网站的标题都保存在一个数组中。在对浏览器进行了如打开新标签、合并窗口、关闭标签之类的操作后,你需要输出所有打开的标签。关掉的标签将从数组中删除,新打开的标签(为简单起见)则添加到数组的末尾。
代码编辑器中显示了此功能的实现,其中包含 <code>tabOpen()</code><code>tabClose()</code>,和 <code>join()</code> 函数。tabs数组是窗口对象的一部分用于储存打开页面的名称。
</section>
## Instructions
<section id="instructions">
<section id='instructions'>
在编辑器中运行代码。它使用了有副作用的方法,导致输出错误。打开标签的最终列表应该是 <code>['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']</code> 但输出会略有不同。
修改 <code>Window.prototype.tabClose</code> 使其删除正确的标签。
</section>
## Tests
@ -18,7 +33,7 @@ localeTitle: 了解使用命令代码的危害
```yml
tests:
- text: 继续前进以了解错误。
- text: <code>finalTabs.tabs</code> 应该是 <code>['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']</code>
testString: assert.deepEqual(finalTabs.tabs, ['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab'])
```
@ -50,8 +65,63 @@ Window.prototype.tabOpen = function (tab) {
// When you close a tab
Window.prototype.tabClose = function (index) {
// Only change code below this line
var tabsBeforeIndex = this.tabs.splice(0, index); // get the tabs before the tab
var tabsAfterIndex = this.tabs.splice(index); // get the tabs after the tab
var tabsAfterIndex = this.tabs.splice(index + 1); // get the tabs after the tab
this.tabs = tabsBeforeIndex.concat(tabsAfterIndex); // join them together
// Only change code above this line
return this;
};
// Let's create three browser windows
var workWindow = new Window(['GMail', 'Inbox', 'Work mail', 'Docs', 'freeCodeCamp']); // Your mailbox, drive, and other work sites
var socialWindow = new Window(['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium']); // Social sites
var videoWindow = new Window(['Netflix', 'YouTube', 'Vimeo', 'Vine']); // Entertainment sites
// Now perform the tab opening, closing, and other operations
var finalTabs = socialWindow
.tabOpen() // Open a new tab for cat memes
.join(videoWindow.tabClose(2)) // Close third tab in video window, and join
.join(workWindow.tabClose(1).tabOpen());
console.log(finalTabs.tabs);
```
</div>
</section>
## Solution
<section id='solution'>
```js
// tabs is an array of titles of each site open within the window
var Window = function(tabs) {
this.tabs = tabs; // we keep a record of the array inside the object
};
// When you join two windows into one window
Window.prototype.join = function (otherWindow) {
this.tabs = this.tabs.concat(otherWindow.tabs);
return this;
};
// When you open a new tab at the end
Window.prototype.tabOpen = function (tab) {
this.tabs.push('new tab'); // let's open a new tab for now
return this;
};
// When you close a tab
Window.prototype.tabClose = function (index) {
var tabsBeforeIndex = this.tabs.slice(0, index); // get the tabs before the tab
var tabsAfterIndex = this.tabs.slice(index + 1); // get the tabs after the tab
this.tabs = tabsBeforeIndex.concat(tabsAfterIndex); // join them together
return this;
@ -67,21 +137,6 @@ var finalTabs = socialWindow
.tabOpen() // Open a new tab for cat memes
.join(videoWindow.tabClose(2)) // Close third tab in video window, and join
.join(workWindow.tabClose(1).tabOpen());
alert(finalTabs.tabs);
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,85 @@
---
id: 587d7b88367417b2b2512b45
title: Use Higher-Order Functions map, filter, or reduce to Solve a Complex Problem
challengeType: 1
forumTopicId: 301311
localeTitle: 使用高阶函数 map、filter 或者 reduce 来解决复杂问题
---
## Description
<section id='description'>
已经接触了高阶函数如 <code>map()</code><code>filter()</code><code>reduce()</code>的使用,是时候用它们来完成一些复杂的挑战了。
</section>
## Instructions
<section id='instructions'>
已经定义了一个函数 <code>squareList</code>。任意组合 <code>map()</code><code>filter()</code><code>reduce()</code> 来完成函数,满足以下条件,当传入实数数组(如,<code>[-3, 4.8, 5, 3, -3.2]</code>)时,返回<em></em>包含正整数的平方的新数组。
<strong>注意:</strong> 函数不应该包含任何形式的 <code>for</code> 或者 <code>while</code> 循环或者 <code>forEach()</code> 函数。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>squareList</code> 应该是一个 <code>function</code>。
testString: assert.typeOf(squareList, 'function'), '<code>squareList</code> should be a <code>function</code>';
- text: 不应该使用 for 或者 while 循环或者 forEach。
testString: assert(!removeJSComments(code).match(/for|while|forEach/g));
- text: 应该使用 <code>map</code>、<code>filter</code> 或者 <code>reduce</code>。
testString: assert(removeJSComments(code).match(/\.(map|filter|reduce)\s*\(/g));
- text: 函数应该返回 <code>array</code>。
testString: assert(Array.isArray(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])));
- text: <code>squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])</code> 应该返回 <code>[16, 1764, 36]</code>。
testString: assert.deepStrictEqual(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]), [16, 1764, 36]);
- text: <code>squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3])</code> 应该返回 <code>[9, 100, 49]</code>。
testString: assert.deepStrictEqual(squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3]), [9, 100, 49]);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
const squareList = (arr) => {
// only change code below this line
return arr;
// only change code above this line
};
// test your code
const squaredIntegers = squareList([-3, 4.8, 5, 3, -3.2]);
console.log(squaredIntegers);
```
</div>
<div id='js-teardown'>
```js
const removeJSComments = str => str.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, '');
```
</div>
</section>
## Solution
<section id='solution'>
```js
const squareList = (arr) => {
const positiveIntegers = arr.filter(num => {
return num >= 0 && Number.isInteger(num);
});
const squaredIntegers = positiveIntegers.map(num => {
return num ** 2;
});
return squaredIntegers;
};
```
</section>

View File

@ -2,28 +2,42 @@
id: 587d7dab367417b2b2512b6e
title: Use the every Method to Check that Every Element in an Array Meets a Criteria
challengeType: 1
videoUrl: ''
localeTitle: 使用every方法检查数组中的每个元素是否符合条件
forumTopicId: 301312
localeTitle: 使用 every 方法检查数组中的每个元素是否符合条件
---
## Description
<section id="description"> <code>every</code>方法都使用数组来检查<em>每个</em>元素是否通过了特定的测试。它返回一个布尔值 - 如果所有值都满足条件,则返回<code>true</code>否则返回<code>false</code> 。例如,以下代码将检查<code>numbers</code>数组中的每个元素是否小于10 <blockquote> var numbers = [1,5,8,0,10,11]; <br> numbers.everyfunctioncurrentValue{ <br> return currentValue &lt;10; <br> }; <br> //返回false </blockquote></section>
<section id='description'>
<code>every</code>方法用于检测数组中<em>所有</em>元素是否都符合指定条件。如果所有元素满足条件,返回布尔值<code>true</code>,反之返回<code>false</code>
举个例子,下面的代码检测数组<code>numbers</code>的所有元素是否都小于 10
```js
var numbers = [1, 5, 8, 0, 10, 11];
numbers.every(function(currentValue) {
return currentValue < 10;
});
// Returns false
```
</section>
## Instructions
<section id="instructions">使用<code>checkPositive</code>函数中的<code>every</code>方法检查<code>arr</code>每个元素是否为正数。该函数应返回一个布尔值。 </section>
<section id='instructions'>
<code>checkPositive</code>函数中使用<code>every</code>方法检查<code>arr</code>中是否所有元素都是正数,函数应返回一个布尔值。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 您的代码应该使用<code>every</code>方法。
- text: 使用<code>every</code>方法。
testString: assert(code.match(/\.every/g));
- text: '<code>checkPositive([1, 2, 3, -4, 5])</code>应返回<code>false</code> 。'
- text: <code>checkPositive([1, 2, 3, -4, 5])</code>应返回<code>false</code>
testString: assert.isFalse(checkPositive([1, 2, 3, -4, 5]));
- text: '<code>checkPositive([1, 2, 3, 4, 5])</code>应返回<code>true</code> 。'
- text: <code>checkPositive([1, 2, 3, 4, 5])</code>应返回<code>true</code>
testString: assert.isTrue(checkPositive([1, 2, 3, 4, 5]));
- text: '<code>checkPositive([1, -2, 3, -4, 5])</code>应返回<code>false</code> 。'
- text: <code>checkPositive([1, -2, 3, -4, 5])</code>应返回<code>false</code>
testString: assert.isFalse(checkPositive([1, -2, 3, -4, 5]));
```
@ -43,7 +57,6 @@ function checkPositive(arr) {
// Add your code above this line
}
checkPositive([1, 2, 3, -4, 5]);
```
</div>
@ -56,6 +69,12 @@ checkPositive([1, 2, 3, -4, 5]);
<section id='solution'>
```js
// solution required
function checkPositive(arr) {
// Add your code below this line
return arr.every(num => num > 0);
// Add your code above this line
}
checkPositive([1, 2, 3, -4, 5]);
```
</section>

View File

@ -2,28 +2,47 @@
id: 587d7b8f367417b2b2512b63
title: Use the filter Method to Extract Data from an Array
challengeType: 1
videoUrl: ''
localeTitle: 使用过滤器方法从数组中提取数据
forumTopicId: 18179
localeTitle: 使用 filter 方法从数组中提取数据
---
## Description
<section id="description">另一个有用的数组函数是<code>Array.prototype.filter()</code> ,或者只是<code>filter()</code><code>filter</code>方法返回一个新数组,该数组最多与原始数组一样长,但通常只有较少的项。 <code>Filter</code>不会像<code>map</code>一样改变原始数组。它需要一个回调函数它将回调内的逻辑应用于数组的每个元素。如果元素根据回调函数中的条件返回true则它将包含在新数组中。 </section>
<section id='description'>
另一个有用的数组方法是<code>filter()</code>(即<code>Array.prototype.filter()</code>)。<code>filter</code>方法会返回一个长度不大于原始数组的新数组。
<code>map</code>一样,<code>Filter</code>不会改变原始数组,它接收一个回调函数,将回调内的逻辑应用于数组的每个元素。新数组包含根据回调函数内条件返回 true 的元素。
回调函数接收三个参数。第一个参数是当前正在被处理的元素,第二个参数是元素的索引,第三个参数是在其上调用 <code>filter</code> 方法的数组。
看下在 <code>users</code> 上使用 <code>filter</code> 方法的例子,返回了一个新数组包含了 30 岁以下的用户。为了简化,例子里只使用了回调函数的第一个参数。
```js
const users = [
{ name: 'John', age: 34 },
{ name: 'Amy', age: 20 },
{ name: 'camperCat', age: 10 }
];
const usersUnder30 = users.filter(user => user.age < 30);
console.log(usersUnder30); // [ { name: 'Amy', age: 20 }, { name: 'camperCat', age: 10 } ]
```
</section>
## Instructions
<section id="instructions">变量<code>watchList</code>对象,其中包含有关多部电影的信息。使用<code>filter</code><code>map</code>的组合返回仅具有<code>title</code><code>rating</code>键的新对象数组,但<code>imdbRating</code>大于或等于8.0。请注意,评级值在对象中保存为字符串,您可能希望将它们转换为数字以对它们执行数学运算。 </section>
<section id='instructions'>
<code>watchList</code>是包含一些电影信息的对象。结合<code>filter</code><code>map</code>返回一个只包含<code>title</code><code>rating</code>属性的新数组,并且<code>imdbRating</code>值大于或等于 8.0。请注意,评级值在对象中保存为字符串,你可能需要将它转换成数字来执行运算。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>watchList</code>变量不应该更改
- text: <code>watchList</code>应保持不变。
testString: assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron");
- text: 您的代码应该使用<code>filter</code>方法。
- text: 使用<code>filter</code>方法。
testString: assert(code.match(/\.filter/g));
- text: 您的代码不应使用<code>for</code>循环。
testString: assert(!code.match(/for\s*?\([\s\S]*?\)/g));
- text: '<code>filteredList</code>应等于<code>[{&quot;title&quot;: &quot;Inception&quot;,&quot;rating&quot;: &quot;8.8&quot;},{&quot;title&quot;: &quot;Interstellar&quot;,&quot;rating&quot;: &quot;8.6&quot;},{&quot;title&quot;: &quot;The Dark Knight&quot;,&quot;rating&quot;: &quot;9.0&quot;},{&quot;title&quot;: &quot;Batman Begins&quot;,&quot;rating&quot;: &quot;8.3&quot;}]</code> 。'
- text: 不能使用<code>for</code>循环。
testString: assert(!code.match(/for\s*?\(.+?\)/g));
- text: '<code>filteredList</code>应等于<code>[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]</code>。'
testString: 'assert.deepEqual(filteredList, [{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]);'
```
@ -38,116 +57,116 @@ tests:
```js
// the global variable
var watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
// Add your code below this line
@ -157,7 +176,6 @@ var filteredList;
// Add your code above this line
console.log(filteredList);
```
</div>
@ -170,6 +188,123 @@ console.log(filteredList);
<section id='solution'>
```js
// solution required
// the global variable
var watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
// Add your code below this line
let filteredList = watchList.filter(e => e.imdbRating >= 8).map( ({Title: title, imdbRating: rating}) => ({title, rating}) );
// Add your code above this line
```
</section>

View File

@ -2,29 +2,51 @@
id: 587d7b8f367417b2b2512b61
title: Use the map Method to Extract Data from an Array
challengeType: 1
videoUrl: ''
localeTitle: 使用映射方法从数组中提取数据
forumTopicId: 18214
localeTitle: 使用 map 方法从数组中提取数据
---
## Description
<section id="description">到目前为止我们已经学会使用纯函数来避免程序中的副作用。此外我们已经看到函数的值仅取决于其输入参数。这仅仅是个开始。顾名思义函数式编程以函数理论为中心。能够将它们作为参数传递给其他函数并从另一个函数返回一个函数是有意义的。函数被认为是JavaScript中的<code>First Class Objects</code> ,这意味着它们可以像任何其他对象一样使用。它们可以保存在变量中,存储在对象中,也可以作为函数参数传递。让我们从一些简单的数组函数开始,这些函数是数组对象原型的方法。在本练习中,我们将查看<code>Array.prototype.map()</code> ,或更简单的<code>map</code> 。请记住, <code>map</code>方法是一种迭代数组中每个项目的方法。在将回调函数应用于每个元素之后,它会创建一个新数组(不更改原始数组)。 </section>
<section id='description'>
目前为止,我们已经学会了使用纯函数来避免程序中的副作用。此外,我们已经看到函数的值仅取决于其输入参数。
这仅仅是个开始。顾名思义,函数式编程以函数理论为中心。
能够将它们作为参数传递给其他函数,和从另一个函数返回一个函数是有意义的。函数在 JavaScript 中被视为<code>First Class Objects</code>,它们可以像任何其他对象一样使用。它们可以保存在变量中,存储在对象中,也可以作为函数参数传递。
让我们从一些简单的数组函数开始,这些函数是数组对象原型上的方法。在本练习中,我们来了解下数组的<code>map</code>方法(即<code>Array.prototype.map()</code>)。
请记住,<code>map</code>方法是迭代数组中每一项的方式之一。在对每个元素应用回调函数后,它会创建一个新数组(不改变原来的数组)。
当调用回调函数时,传入了三个参数。第一个参数是当前正在处理的数组项,第二个参数是当前数组项的索引值,第三个参数是在其上调用 <code>map</code> 方法的数组。
看下在 <code>users</code> 上使用 <code>map</code> 方法的例子,返回了一个新数组只包含了用户的名字。为了简化,例子里只使用了回调函数的第一个参数。
```js
const users = [
{ name: 'John', age: 34 },
{ name: 'Amy', age: 20 },
{ name: 'camperCat', age: 10 }
];
const names = users.map(user => user.name);
console.log(names); // [ 'John', 'Amy', 'camperCat' ]
```
</section>
## Instructions
<section id="instructions"> <code>watchList</code>数组保存包含多部电影信息的对象。使用<code>map</code><code>watchList</code>提取标题和评级,并将新数组保存在<code>rating</code>变量中。编辑器中的代码当前使用<code>for</code>循环来执行此操作,将循环功能替换为<code>map</code>表达式。 </section>
<section id='instructions'>
<code>watchList</code>数组保存了包含一些电影信息的对象。使用<code>map</code><code>watchList</code>中提取标题(<code>title</code>)和评分(<code>rating</code>),并将新数组保存在<code>rating</code>变量里。目前编辑器中的代码是使用<code>for</code>循环实现,使用<code>map</code>表达式替换循环功能。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>watchList</code>变量不应该更改。
- text: <code>watchList</code>不能被改
testString: assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron");
- text: 的代码不使用<code>for</code>循环。
testString: assert(!removeJSComments(code).match(/for\s*?\([\s\S]*?\)/));
- text: 的代码应使用<code>map</code>方法。
- text: 的代码不使用<code>for</code>循环。
testString: assert(!removeJSComments(code).match(/for\s*?\(.*?\)/));
- text: 的代码应使用<code>map</code>方法。
testString: assert(code.match(/\.map/g));
- text: '<code>rating</code>应等于<code>[{&quot;title&quot;:&quot;Inception&quot;,&quot;rating&quot;:&quot;8.8&quot;},{&quot;title&quot;:&quot;Interstellar&quot;,&quot;rating&quot;:&quot;8.6&quot;},{&quot;title&quot;:&quot;The Dark Knight&quot;,&quot;rating&quot;:&quot;9.0&quot;},{&quot;title&quot;:&quot;Batman Begins&quot;,&quot;rating&quot;:&quot;8.3&quot;},{&quot;title&quot;:&quot;Avatar&quot;,&quot;rating&quot;:&quot;7.9&quot;}]</code>'
testString: 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"}]);
- text: '<code>rating</code>应等于<code>[{"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"}]</code>.'
testString: 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"}]));
```
@ -38,134 +60,140 @@ tests:
```js
// the global variable
var watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
// Add your code below this line
var rating = [];
var ratings = [];
for(var i=0; i < watchList.length; i++){
rating.push({title: watchList[i]["Title"], rating: watchList[i]["imdbRating"]});
ratings.push({title: watchList[i]["Title"], rating: watchList[i]["imdbRating"]});
}
// Add your code above this line
console.log(rating);
console.log(JSON.stringify(ratings));
```
</div>
### After Test
<div id='js-teardown'>
```js
const removeJSComments = str => str.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, '');
```
</div>
</section>
@ -173,6 +201,126 @@ console.log(rating);
<section id='solution'>
```js
// solution required
// the global variable
var watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
var ratings = watchList.map(function(movie) {
return {
title: movie["Title"],
rating: movie["imdbRating"]
}
});
```
</section>

View File

@ -2,29 +2,73 @@
id: 587d7da9367417b2b2512b68
title: Use the reduce Method to Analyze Data
challengeType: 1
videoUrl: ''
localeTitle: 使用reduce方法分析数据
forumTopicId: 301313
localeTitle: 使用 reduce 方法分析数据
---
## Description
<section id="description"> <code>Array.prototype.reduce()</code>或简称<code>reduce()</code>是JavaScript中所有数组操作中最常见的。您可以使用<code>reduce</code>方法解决几乎任何数组处理问题。 <code>filter</code><code>map</code>方法不是这种情况,因为它们不允许阵列的两个不同元素之间的交互。例如,如果要比较数组的元素或将它们添加到一起,则<code>filter</code><code>map</code>无法处理它。 <code>reduce</code>方法允许更一般的数组处理形式,并且可以显示<code>filter</code><code>map</code>都可以作为<code>reduce</code>的特殊应用派生。但是,在我们到达之前,让我们先练习使用<code>reduce</code></section>
<section id='description'>
<code>reduce()</code>(即<code>Array.prototype.reduce()</code>),是 JavaScript 所有数组操作中最常用的方法。几乎可以用<code>reduce</code>方法解决所有数组处理问题。
<code>reduce</code>方法是处理数组更通用的方式,而且<code>filter</code><code>map</code>方法都可以当作是<code>reduce</code>的特殊实现。
<code> reduce </code>方法遍历数组中的每个项目并返回单个值(即字符串、数字、对象、数组)。 这是通过在每次迭代中调用一个回调函数来实现的。
回调函数接受四个参数。第一个参数称为叠加器,它是上一次迭代中回调函数的返回值,第二个参数是当前正在处理的数组元素,第三个参数是该参数的索引,第四个参数是在其上调用 <code>reduce</code> 方法的数组。
除了回调函数,<code>reduce</code> 还有一个额外的参数做为叠加器的初始值。如果没有第二个参数,会跳过第一次迭代,第二次迭代给叠加器传入数组的第一个元素。
见下面的例子,给 <code>users</code> 数组使用 <code>reduce</code> 方法,返回所有用户数组的和。为了简化,例子仅使用了回调函数的第一个参数和第二个参数。
```js
const users = [
{ name: 'John', age: 34 },
{ name: 'Amy', age: 20 },
{ name: 'camperCat', age: 10 }
];
const sumOfAges = users.reduce((sum, user) => sum + user.age, 0);
console.log(sumOfAges); // 64
```
在另一个例子里,查看如何返回一个包含用户名称做为属性,其年龄做为值的对象。
```js
const users = [
{ name: 'John', age: 34 },
{ name: 'Amy', age: 20 },
{ name: 'camperCat', age: 10 }
];
const usersObj = users.reduce((obj, user) => {
obj[user.name] = user.age;
return obj;
}, {});
console.log(usersObj); // { John: 34, Amy: 20, camperCat: 10 }
```
</section>
## Instructions
<section id="instructions">变量<code>watchList</code>对象,其中包含有关多部电影的信息。使用<code>reduce</code>查找<strong>Christopher Nolan指导</strong>的电影的平均IMDB评级。回想一下先前的挑战如何<code>filter</code>数据并将数据<code>map</code>到您需要的地方。您可能需要创建其他变量,但将最终平均值保存到变量<code>averageRating</code> 。请注意,评级值在对象中保存为字符串,在用于任何数学运算之前需要转换为数字。 </section>
<section id='instructions'>
<code>watchList</code>变量中包含一组存有多部电影信息对象。使用<code>reduce</code>查找由<strong> Christopher Nolan 导演</strong>的电影的 IMDB 评级平均值。回想一下之前的挑战,如何<code>filter</code>数据,以及使用<code>map</code>来获取你想要的数据。你可能需要创建一些变量,但是请将最后的平均值保存到<code>averageRating</code>变量中。请注意,评级在对象中是字符串,需要将其转换为数字再用于数学运算。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>watchList</code>变量不应该更改
testString: 'assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron", "The <code>watchList</code> variable should not change.");'
- text: 您的代码应使用<code>reduce</code>方法。
testString: 'assert(code.match(/\.reduce/g), "Your code should use the <code>reduce</code> method.");'
- text: <code>averageRating</code>应等于8.675。
testString: 'assert(averageRating == 8.675, "The <code>averageRating</code> should equal 8.675.");'
- text: 您的代码不应使用<code>for</code>循环。
testString: 'assert(!code.match(/for\s*?\(.*\)/g), "Your code should not use a <code>for</code> loop.");'
- text: <code>watchList</code>应保持不变。
testString: assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron");
- text: 使用<code>reduce</code>方法。
testString: assert(code.match(/\.reduce/g));
- text: The<code>averageRating</code>应等于 8.675。
testString: assert(getRating(watchList) === 8.675);
- text: 不能使用<code>for</code>循环。
testString: assert(!code.match(/for\s*?\(.*\)/g));
- text: 在修改 <code>watchList</code> 对象后应该返回正确的输出。
testString: assert(getRating(watchList.filter((_, i) => i < 1 || i > 2)) === 8.55);
```
@ -38,126 +82,127 @@ tests:
```js
// the global variable
var watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
// Add your code below this line
function getRating(watchList){
// Add your code below this line
var averageRating;
var averageRating;
// Add your code above this line
console.log(averageRating);
// Add your code above this line
return averageRating;
}
console.log(getRating(watchList));
```
</div>
@ -170,6 +215,129 @@ console.log(averageRating);
<section id='solution'>
```js
// solution required
// the global variable
var watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
function getRating(watchList){
var averageRating;
const rating = watchList
.filter(obj => obj.Director === "Christopher Nolan")
.map(obj => Number(obj.imdbRating));
averageRating = rating.reduce((accum, curr) => accum + curr)/rating.length;
return averageRating;
}
```
</section>

View File

@ -2,28 +2,42 @@
id: 587d7dab367417b2b2512b6f
title: Use the some Method to Check that Any Elements in an Array Meet a Criteria
challengeType: 1
videoUrl: ''
localeTitle: 使用某些方法检查阵列中的任何元素是否符合条件
forumTopicId: 301314
localeTitle: 使用 some 方法检查数组中是否有元素是否符合条件
---
## Description
<section id="description"> <code>some</code>方法适用于数组,以检查是否有<em>任何</em>元素通过了特定的测试。它返回一个布尔值 - 如果任何值满足条件,则返回<code>true</code>否则返回<code>false</code> 。例如,以下代码将检查<code>numbers</code>数组中的任何元素是否小于10 <blockquote> var number = [10,50,8,220,110,11]; <br> numbers.somefunctioncurrentValue{ <br> return currentValue &lt;10; <br> }; <br> //返回true </blockquote></section>
<section id='description'>
<code>some</code>方法用于检测数组中<em>任何</em>元素是否满足指定条件。如果有一个元素满足条件,返回布尔值<code>true</code>,反之返回<code>false</code>
举个例子,下面的代码检测数组<code>numbers</code>中是否有元素小于10
```js
var numbers = [10, 50, 8, 220, 110, 11];
numbers.some(function(currentValue) {
return currentValue < 10;
});
// Returns true
```
</section>
## Instructions
<section id="instructions">使用<code>checkPositive</code>函数中的<code>some</code>方法检查<code>arr</code>任何元素是否为正数。该函数应返回一个布尔值。 </section>
<section id='instructions'>
<code>checkPositive</code>函数值中使用<code>some</code>检查<code>arr</code>中是否有元素为正数,函数应返回一个布尔值。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 您的代码应该使用<code>some</code>方法。
- text: 应该使用<code>some</code>method.
testString: assert(code.match(/\.some/g));
- text: '<code>checkPositive([1, 2, 3, -4, 5])</code>应返回<code>true</code> 。'
- text: <code>checkPositive([1, 2, 3, -4, 5])</code>应返回<code>true</code>
testString: assert(checkPositive([1, 2, 3, -4, 5]));
- text: '<code>checkPositive([1, 2, 3, 4, 5])</code>应返回<code>true</code> 。'
- text: <code>checkPositive([1, 2, 3, 4, 5])</code>应返回<code>true</code>
testString: assert(checkPositive([1, 2, 3, 4, 5]));
- text: '<code>checkPositive([-1, -2, -3, -4, -5])</code>应返回<code>false</code> 。'
- text: <code>checkPositive([-1, -2, -3, -4, -5])</code>应返回<code>false</code>
testString: assert(!checkPositive([-1, -2, -3, -4, -5]));
```
@ -43,7 +57,6 @@ function checkPositive(arr) {
// Add your code above this line
}
checkPositive([1, 2, 3, -4, 5]);
```
</div>
@ -56,6 +69,12 @@ checkPositive([1, 2, 3, -4, 5]);
<section id='solution'>
```js
// solution required
function checkPositive(arr) {
// Add your code below this line
return arr.some(elem => elem > 0);
// Add your code above this line
}
checkPositive([1, 2, 3, -4, 5]);
```
</section>