diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/add-elements-to-the-end-of-an-array-using-concat-instead-of-push.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/add-elements-to-the-end-of-an-array-using-concat-instead-of-push.chinese.md index b98550436f..f443b664e0 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/add-elements-to-the-end-of-an-array-using-concat-instead-of-push.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/add-elements-to-the-end-of-an-array-using-concat-instead-of-push.chinese.md @@ -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 -
函数式编程就是创建和使用非变异函数。最后一个挑战是将concat方法作为一种将数组组合成新数组而不改变原始数组的方法。将concatpush方法进行比较。 Push将一个项添加到调用它的同一个数组的末尾,这会改变该数组。这是一个例子:
var arr = [1,2,3];
arr.push([4,5,6]);
// arr更改为[1,2,3,[4,5,6]]
//不是函数式编程方式
Concat提供了一种在数组末尾添加新项目而无任何变异副作用的方法。
+
+函数式编程就是创建和使用具有不变性的函数。 +上一个挑战介绍了concat方法,这是一种在不改变原始数组的前提下,将数组组合成新数组的方法。将concat方法与push方法做比较,Push将元素添加到调用它的数组的末尾,这样会改变该数组。举个例子: + +```js +var arr = [1, 2, 3]; +arr.push([4, 5, 6]); +// arr is changed to [1, 2, 3, [4, 5, 6]] +// Not the functional programming way +``` + +Concat方法可以将新项目添加到数组末尾,而不产生任何变化。 +
## Instructions -
更改nonMutatingPush函数,使其使用concatnewItem添加到original结尾而不是push 。该函数应返回一个数组。
+
+修改nonMutatingPush函数,用concat替代pushnewItem添加到original末尾,该函数应返回一个数组。 +
## Tests
```yml tests: - - text: 您的代码应使用concat方法。 + - text: 应该使用concat方法。 testString: assert(code.match(/\.concat/g)); - - text: 您的代码不应使用push方法。 + - text: 不能使用push方法。 testString: assert(!code.match(/\.push/g)); - - text: 第first数组不应该改变。 + - text: 不能改变first数组。 testString: assert(JSON.stringify(first) === JSON.stringify([1, 2, 3])); - - text: second数组不应该改变。 + - text: 不能改变second数组。 testString: assert(JSON.stringify(second) === JSON.stringify([4, 5])); - - text: 'nonMutatingPush([1, 2, 3], [4, 5])应该返回[1, 2, 3, 4, 5] 。' + - text: nonMutatingPush([1, 2, 3], [4, 5])应返回[1, 2, 3, 4, 5]。 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); - ``` @@ -60,6 +73,12 @@ nonMutatingPush(first, second);
```js -// solution required +function nonMutatingPush(original, newItem) { + return original.concat(newItem); +} +var first = [1, 2, 3]; +var second = [4, 5]; +nonMutatingPush(first, second); ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/apply-functional-programming-to-convert-strings-to-url-slugs.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/apply-functional-programming-to-convert-strings-to-url-slugs.chinese.md index 95a9b0c39b..789707cf4b 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/apply-functional-programming-to-convert-strings-to-url-slugs.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/apply-functional-programming-to-convert-strings-to-url-slugs.chinese.md @@ -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 -
最后几个挑战涵盖了许多遵循函数式编程原理的有用数组和字符串方法。我们还学习了reduce ,这是一种用于将问题简化为更简单形式的强大方法。从计算平均值到排序,可以通过应用它来实现任何阵列操作。回想一下mapfilterreduce特例。让我们结合我们学到的东西来解决实际问题。许多内容管理站点(CMS)将帖子的标题添加到URL的一部分以用于简单的书签目的。例如,如果您编写一个标题为“Stop Using Reduce”的Medium帖子,则URL可能会包含某种形式的标题字符串(“... / stop-using-reduce”)。您可能已经在freeCodeCamp网站上注意到了这一点。
+
+最后几个挑战中涵盖了许多符合函数式编程原则并在处理数组和字符串中非常有用的方法。我们还学习了强大的、可以将问题简化为更简单形式的reduce方法,从计算平均值到排序,任何数组操作都可以用它来实现。回想一下,mapfilter方法都是reduce的特殊实现。 +让我们把学到的知识结合起来解决一个实际问题。 +许多内容管理站点(CMS)为了让添加书签更简单,会将帖子的标题添加到 URL 上。举个例子,如果你写了一篇标题为 "Stop Using Reduce" 的帖子,URL很可能会包含标题字符串的某种形式 (如:".../stop-using-reduce"),你可能已经在 freeCodeCamp 网站上注意到了这一点。 +
## Instructions -
填写urlSlug函数,以便转换字符串title并返回URL的连字符版本。您可以使用本节中介绍的任何方法,也不要使用replace 。以下是要求:输入是一个带空格和标题字的字符串输出是一个字符串,单词之间的空格用连字符替换( - )输出应该是所有低位字母输出不应该有任何空格
+
+填写urlSlug函数,将字符串title转换成带有连字符号的 URL。您可以使用本节中介绍的任何方法,但不要用replace方法。以下是本次挑战的要求: +输入包含空格和标题大小写单词的字符串 +输出字符串,单词之间的空格用连字符(-)替换 +输出应该是小写字母 +输出不应有任何空格 +
## Tests
```yml tests: - - text: globalTitle变量不应该更改。 + - text: globalTitle变量应保持不变。 testString: assert(globalTitle === "Winter Is Coming"); - - text: 您的代码不应使用replace方法来应对此挑战。 + - text: 在此挑战中不能使用replace方法。 testString: assert(!code.match(/\.replace/g)); - - text: urlSlug("Winter Is Coming")应该回归"winter-is-coming" 。 + - text: "urlSlug('Winter Is Coming')应返回'winter-is-coming'。" testString: assert(urlSlug("Winter Is Coming") === "winter-is-coming"); - - text: urlSlug(" Winter Is Coming")应该回归"winter-is-coming" 。 + - text: "urlSlug(' Winter Is  Coming')应返回'winter-is-coming'。" testString: assert(urlSlug(" Winter Is Coming") === "winter-is-coming"); - - text: urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")应该回归"a-mind-needs-books-like-a-sword-needs-a-whetstone" 。 + - text: "urlSlug('A Mind Needs Books Like A Sword Needs A Whetstone')应返回'a-mind-needs-books-like-a-sword-needs-a-whetstone'。" testString: assert(urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone") === "a-mind-needs-books-like-a-sword-needs-a-whetstone"); - - text: urlSlug("Hold The Door")应该返回"hold-the-door" 。 + - text: "urlSlug('Hold The Door')应返回'hold-the-door'。" 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" - ``` @@ -64,6 +73,16 @@ var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"
```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" ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/avoid-mutations-and-side-effects-using-functional-programming.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/avoid-mutations-and-side-effects-using-functional-programming.chinese.md index 09843cd355..bceeb4551e 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/avoid-mutations-and-side-effects-using-functional-programming.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/avoid-mutations-and-side-effects-using-functional-programming.chinese.md @@ -2,24 +2,33 @@ id: 587d7b8e367417b2b2512b5e title: Avoid Mutations and Side Effects Using Functional Programming challengeType: 1 -videoUrl: '' -localeTitle: 使用功能编程避免突变和副作用 +forumTopicId: 301228 +localeTitle: 使用函数式编程避免变化和副作用 --- ## Description -
如果您还没有弄明白,上一次挑战中的问题是使用tabClose()函数中的splice调用。不幸的是, splice更改了它所调用的原始数组,因此对它的第二次调用使用了一个修改过的数组,并给出了意想不到的结果。这是一个更大模式的一个小例子 - 你在一个变量,数组或一个对象上调用一个函数,该函数改变了对象中的变量或其他东西。函数式编程的核心原则之一是不改变事物。变化导致错误。知道你的函数不会改变任何东西,包括函数参数或任何全局变量,更容易防止错误。前面的例子没有任何复杂的操作,但是splice方法改变了原始数组,并导致了一个bug。回想一下,在函数式编程中,改变或改变事物称为mutation ,结果称为side effect 。理想情况下,函数应该是pure function ,这意味着它不会产生任何副作用。让我们尝试掌握这门学科,不要改变代码中的任何变量或对象。
+
+如果你还没想通,上一个挑战的问题出在tabClose()函数里的splice。不幸的是,splice修改了调用它的原始数组,所以第二次调用它时是基于修改后的数组,才给出了意料之外的结果。 +这是一个小例子,还有更广义的定义——在变量,数组或对象上调用一个函数,这个函数会改变对象中的变量或其他东西。 +函数式编程的核心原则之一是不改变任何东西。变化会导致错误。如果一个函数不改变传入的参数、全局变量等数据,那么它造成问题的可能性就会小很多。 +前面的例子没有任何复杂的操作,但是splice方法改变了原始数组,导致 bug 产生。 +回想一下,在函数式编程中,改变或变更叫做mutation,这种改变的结果叫做“副作用”(side effect)。理想情况下,函数应该是不会产生任何副作用的纯函数。 +让我们尝试掌握这个原则:不要改变代码中的任何变量或对象。 +
## Instructions -
填写函数incrementer的代码,使其返回全局变量fixedValue的值增加1。
+
+填写incrementer函数的代码,使其返回全局变量fixedValue的值增加 1。 +
## Tests
```yml tests: - - text: 您的函数incrementer不应更改fixedValue的值。 + - text: incrementer函数不能改变fixedValue的值。 testString: assert(fixedValue === 4); - - text: 您的incrementer函数应返回一个大于fixedValue值的值。 + - text: incrementer函数应返回比fixedValue变量更大的值。 testString: assert(newValue === 5); ``` @@ -44,7 +53,6 @@ function incrementer () { var newValue = incrementer(); // Should equal 5 console.log(fixedValue); // Should print 4 - ``` @@ -57,6 +65,13 @@ console.log(fixedValue); // Should print 4
```js -// solution required +var fixedValue = 4 + +function incrementer() { + return fixedValue + 1 +} + +var newValue = incrementer(); // Should equal 5 ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/combine-an-array-into-a-string-using-the-join-method.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/combine-an-array-into-a-string-using-the-join-method.chinese.md index 749106dfb5..8342f65537 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/combine-an-array-into-a-string-using-the-join-method.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/combine-an-array-into-a-string-using-the-join-method.chinese.md @@ -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 -
join方法用于将数组的元素连接在一起以创建字符串。它需要一个用于分隔字符串中数组元素的分隔符的参数。这是一个例子:
var arr = [“你好”,“世界”];
var str = arr.join(“”);
//将str设置为“Hello World”
+
+join方法用来把数组中的所有元素放入一个字符串,并通过指定的分隔符参数进行分隔。 +举个例子: + +```js +var arr = ["Hello", "World"]; +var str = arr.join(" "); +// Sets str to "Hello World" +``` + +
## Instructions -
使用sentensify函数内的join方法(以及其他方法)从字符串str的单词创建一个句子。该函数应返回一个字符串。例如,“我喜欢星球大战”将被转换为“我喜欢星球大战”。对于此挑战,请勿使用replace方法。
+
+在函数sentensify内用join方法(及其他方法)用字符串str中的单词造句,这个函数应返回一个字符串。举个例子,"I-like-Star-Wars" 会被转换成 "I like Star Wars"。在此挑战中请勿使用replace方法。 +
## Tests
```yml tests: - - text: 您的代码应使用join方法。 + - text: 应使用join方法。 testString: assert(code.match(/\.join/g)); - - text: 您的代码不应使用replace方法。 + - text: 不能使用replace方法。 testString: assert(!code.match(/\.replace/g)); - - text: sentensify("May-the-force-be-with-you")应该返回一个字符串。 + - text: "sentensify('May-the-force-be-with-you')应返回一个字符串" testString: assert(typeof sentensify("May-the-force-be-with-you") === "string"); - - text: sentensify("May-the-force-be-with-you")应该返回"May the force be with you" 。 + - text: "sentensify('May-the-force-be-with-you')应返回'May the force be with you'。" testString: assert(sentensify("May-the-force-be-with-you") === "May the force be with you"); - - text: sentensify("The.force.is.strong.with.this.one")应该返回"The force is strong with this one" 。 + - text: "sentensify('The.force.is.strong.with.this.one')应返回'The force is strong with this one'。" testString: assert(sentensify("The.force.is.strong.with.this.one") === "The force is strong with this one"); - - text: 'sentensify("There,has,been,an,awakening")应该回归"There has been an awakening" 。' + - text: "sentensify('There,has,been,an,awakening')应返回'There has been an awakening'。" 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"); - ``` @@ -60,6 +71,11 @@ sentensify("May-the-force-be-with-you");
```js -// solution required +function sentensify(str) { + // Add your code below this line + return str.split(/\W/).join(' '); + // Add your code above this line +} ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/combine-two-arrays-using-the-concat-method.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/combine-two-arrays-using-the-concat-method.chinese.md index 618e769f4e..d990c85d8c 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/combine-two-arrays-using-the-concat-method.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/combine-two-arrays-using-the-concat-method.chinese.md @@ -2,28 +2,38 @@ id: 587d7da9367417b2b2512b66 title: Combine Two Arrays Using the concat Method challengeType: 1 -videoUrl: '' -localeTitle: 使用concat方法组合两个数组 +forumTopicId: 301229 +localeTitle: 使用 concat 方法组合两个数组 --- ## Description -
Concatenation意味着端到端地连接项目。 JavaScript为字符串和数组提供了以相同方式工作的concat方法。对于数组,该方法在一个上调用,然后另一个数组作为concat的参数提供,该数组被添加到第一个数组的末尾。它返回一个新数组,不会改变任何一个原始数组。这是一个例子:
[1,2,3] .concat([4,5,6]);
//返回一个新数组[1,2,3,4,5,6]
+
+Concatenation意思是将元素连接到尾部。同理,JavaScript 为字符串和数组提供了concat方法。对数组来说,在一个数组上调用concat方法,然后提供另一个数组作为参数添加到第一个数组末尾,返回一个新数组,不会改变任何一个原始数组。举个例子: + +```js +[1, 2, 3].concat([4, 5, 6]); +// 返回新数组 [1, 2, 3, 4, 5, 6] +``` + +
## Instructions -
使用nonMutatingConcat函数中的concat方法attachoriginal的结尾。该函数应返回连接数组。
+
+在nonMutatingConcat函数里使用concat,将attach拼接到original尾部,返回拼接后的数组。 +
## Tests
```yml tests: - - text: 您的代码应使用concat方法。 + - text: 应该使用concat方法。 testString: assert(code.match(/\.concat/g)); - - text: 第first数组不应该改变。 + - text: 不能改变first数组。 testString: assert(JSON.stringify(first) === JSON.stringify([1, 2, 3])); - - text: second数组不应该改变。 + - text: 不能改变second数组。 testString: assert(JSON.stringify(second) === JSON.stringify([4, 5])); - - text: 'nonMutatingConcat([1, 2, 3], [4, 5])应该返回[1, 2, 3, 4, 5] 。' + - text: nonMutatingConcat([1, 2, 3], [4, 5])应返回[1, 2, 3, 4, 5]。 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); - ``` @@ -58,6 +67,14 @@ nonMutatingConcat(first, second);
```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); ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype.chinese.md index 682505ed01..fd183b17dc 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype.chinese.md @@ -2,24 +2,31 @@ id: 587d7b8f367417b2b2512b62 title: Implement map on a Prototype challengeType: 1 -videoUrl: '' -localeTitle: 在Prototype上实现地图 +forumTopicId: 301230 +localeTitle: 在原型上实现 map 方法 --- ## Description -
正如您在应用Array.prototype.map()或之前简单地map()所看到的那样, map方法返回一个与调用它的长度相同的数组。它也不会改变原始数组,只要它的回调函数不会。换句话说, map是一个纯函数,它的输出完全取决于它的输入。另外,它需要另一个函数作为其参数。它会教我们很多关于map的尝试实现它的一个版本,它的行为与带有for循环或Array.prototype.forEach()Array.prototype.map()完全相同。注意:允许纯函数改变在其范围内定义的局部变量,但是,最好也避免使用它。
+
+我们之前用map方法(即Array.prototype.map())返回一个与调用它的数组长度相同的数组。只要它的回调函数不改变原始数组,它就不会改变原始数组。 +换句话说,map是一个纯函数,它的输出仅取决于输入的数组和作为参数传入的回调函数。 +为了加深对map方法的理解,现在我们来用forArray.prototype.forEach()自己实现一下这个方法。 +注意:纯函数可以改变其作用域内定义的局部变量,但我们最好不要这样做。 +
## Instructions -
编写自己的Array.prototype.myMap() ,其行为应与Array.prototype.map()完全相同。您可以使用for循环或forEach方法。
+
+写一个和Array.prototype.map()一样的Array.prototype.myMap()。你可以用for循环或者forEach方法。 +
## Tests
```yml tests: - - text: 'new_s应该等于[46, 130, 196, 10] new_s [46, 130, 196, 10] 。' + - text: new_s应等于[46, 130, 196, 10]。 testString: assert(JSON.stringify(new_s) === JSON.stringify([46, 130, 196, 10])); - - text: 您的代码不应使用map方法。 + - text: 不能使用map方法。 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; }); - ``` @@ -60,6 +66,23 @@ var new_s = s.myMap(function(item){
```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; +}); ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/implement-the-filter-method-on-a-prototype.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/implement-the-filter-method-on-a-prototype.chinese.md index 20759e016d..97f789d126 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/implement-the-filter-method-on-a-prototype.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/implement-the-filter-method-on-a-prototype.chinese.md @@ -2,24 +2,29 @@ id: 587d7b8f367417b2b2512b64 title: Implement the filter Method on a Prototype challengeType: 1 -videoUrl: '' -localeTitle: 在Prototype上实现过滤器方法 +forumTopicId: 301231 +localeTitle: 在原型上实现 filter 方法 --- ## Description -
如果我们尝试实现与Array.prototype.filter()完全相同的版本,它会教会我们很多关于filter方法的内容。它可以使用for循环或Array.prototype.forEach() 。注意:允许纯函数改变在其范围内定义的局部变量,但是,最好也避免使用它。
+
+为了加深对filter的理解,现在我们来自己实现一下Array.prototype.filter()方法。可以用for循环或Array.prototype.forEach()。 +请注意:纯函数可以改变其作用域内定义的局部变量,但我们最好不要这样做。 +
## Instructions -
编写自己的Array.prototype.myFilter() ,其行为应与Array.prototype.filter()完全相同。您可以使用for循环或Array.prototype.forEach()方法。
+
+编写一个和Array.prototype.filter()功能一样的Array.prototype.myFilter()方法。你可以用for循环或Array.prototype.forEach()方法。 +
## Tests
```yml tests: - - text: 'new_s应该等于[23, 65, 5] new_s [23, 65, 5] 。' + - text: new_s应等于[23, 65, 5]。 testString: assert(JSON.stringify(new_s) === JSON.stringify([23, 65, 5])); - - text: 您的代码不应使用filter方法。 + - text: 不能使用filter方法。 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; }); - ``` @@ -60,6 +64,23 @@ var new_s = s.myFilter(function(item){
```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 diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/introduction-to-currying-and-partial-application.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/introduction-to-currying-and-partial-application.chinese.md index bbaa5c9044..92268957e6 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/introduction-to-currying-and-partial-application.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/introduction-to-currying-and-partial-application.chinese.md @@ -2,28 +2,73 @@ id: 587d7dab367417b2b2512b70 title: Introduction to Currying and Partial Application challengeType: 1 -videoUrl: '' -localeTitle: Currying和Partial Application简介 +forumTopicId: 301232 +localeTitle: 函数柯里化 --- ## Description -
函数的arity是它需要的参数数量。 Currying一个功能装置,以n的函数转换arity为N的功能arity 1。换言之,它重构的功能,因此采用一个参数,然后返回另一个函数,它的下一个参数,依此类推。这是一个例子:
//非咖喱功能
function unCurried(x,y){
返回x + y;
}

// Curried功能
function curried(x){
return函数(y){
返回x + y;
}
}
curried(1)(2)//返回3
如果您无法一次为函数提​​供所有参数,则在程序中这很有用。您可以将每个函数调用保存到一个变量中,该变量将保存返回的函数引用,该引用在可用时接受下一个参数。以下是使用上面示例中的curried函数的示例:
//在部分中调用curried函数:
var funcForY = curried(1);
的console.log(funcForY(2)); //打印3
类似地, partial application可以描述为一次向函数应用一些参数并返回应用于更多参数的另一个函数。这是一个例子:
//公正的功能
功能公正(x,y,z){
return x + y + z;
}
var partialFn = impartial.bind(this,1,2);
partialFn(10); //返回13
+
+arity是函数所需的形参的数量。函数柯里化意思是把接受多个arity的函数变换成接受单一arity的函数。 +换句话说,就是重构函数让它接收一个参数,然后返回接收下一个参数的函数,依此类推。 +举个例子: + +```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 +``` + +柯里化在不能一次为函数提供所有参数情况下很有用。因为它可以将每个函数的调用保存到一个变量中,该变量将保存返回的函数引用,该引用在下一个参数可用时接受该参数。下面是使用柯里化函数的例子: + +```js +// Call a curried function in parts: +var funcForY = curried(1); +console.log(funcForY(2)); // Prints 3 +``` + +类似地,局部应用的意思是一次对一个函数应用几个参数,然后返回另一个应用更多参数的函数。 +举个例子: + +```js +//Impartial function +function impartial(x, y, z) { + return x + y + z; +} +var partialFn = impartial.bind(this, 1, 2); +partialFn(10); // Returns 13 +``` + +
## Instructions -
填写add函数的主体,以便使用currying来添加参数xyz
+
+填写add函数主体部分,用柯里化添加参数xyz. +
## Tests
```yml tests: - - text: add(10)(20)(30)应该返回60 。 + - text: add(10)(20)(30)应返回60。 testString: assert(add(10)(20)(30) === 60); - - text: add(1)(2)(3)应该返回6 。 + - text: add(1)(2)(3)应返回6。 testString: assert(add(1)(2)(3) === 6); - - text: add(11)(22)(33)应该返回66 。 + - text: add(11)(22)(33)应返回66。 testString: assert(add(11)(22)(33) === 66); - - text: 您的代码应包含返回x + y + z的final语句。 + - text: 应返回x + y + z的最终结果。 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); - ``` @@ -56,6 +100,7 @@ add(10)(20)(30);
```js -// solution required +const add = x => y => z => x + y + z ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/learn-about-functional-programming.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/learn-about-functional-programming.chinese.md index 4c877f723e..b5f6780510 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/learn-about-functional-programming.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/learn-about-functional-programming.chinese.md @@ -2,24 +2,34 @@ id: 587d7b8d367417b2b2512b5b title: Learn About Functional Programming challengeType: 1 -videoUrl: '' -localeTitle: 了解功能编程 +forumTopicId: 301233 +localeTitle: 学习函数式编程 --- ## Description -
功能编程是一种编程风格,其中解决方案是简单,独立的功能,在功能范围之外没有任何副作用。 INPUT -> PROCESS -> OUTPUT功能编程是关于:1)隔离函数 - 不依赖于程序的状态,其中包括可能发生变化的全局变量2)纯函数 - 相同的输入总是给出相同的输出3)副作用有限的功能 - 对功能外部程序状态的任何改变或突变都要仔细控制
+
+函数式编程是一种方案简单、功能独立、对作用域外没有任何副作用的编程范式。 +INPUT -> PROCESS -> OUTPUT +函数式编程: +1)功能独立——不依赖于程序的状态(比如可能发生变化的全局变量); +2)纯函数——同一个输入永远能得到同一个输出; +3)有限的副作用——可以严格地限制函数外部对状态的更改。 +
## Instructions -
freeCodeCamp的成员碰巧爱茶。在代码编辑器中,已经为您定义了prepareTeagetTea函数。调用getTea函数为团队获取40杯茶,并将它们存储在tea4TeamFCC变量中。
+
+freeCodeCamp 成员在 love tea 的故事。 +在代码编辑器中,已经为你定义好了prepareTeagetTea函数。调用getTea函数为团队准备 40 杯茶,并将它们存储在tea4TeamFCC变量里。 +
## Tests
```yml tests: - - text: tea4TeamFCC变量应该为团队提供40杯茶。 + - text: tea4TeamFCC变量里应有 40 杯为团队准备的茶。 testString: assert(tea4TeamFCC.length === 40); - - text: tea4TeamFCC变量应该拿着一杯绿茶。 + - text: tea4TeamFCC变量里应有 greenTea。 testString: assert(tea4TeamFCC[0] === 'greenTea'); ``` @@ -61,7 +71,6 @@ const tea4TeamFCC = null; // :( // Add your code above this line console.log(tea4TeamFCC); - ``` @@ -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); ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/pass-arguments-to-avoid-external-dependence-in-a-function.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/pass-arguments-to-avoid-external-dependence-in-a-function.chinese.md index 5ef7985478..e18e79e511 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/pass-arguments-to-avoid-external-dependence-in-a-function.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/pass-arguments-to-avoid-external-dependence-in-a-function.chinese.md @@ -2,26 +2,36 @@ id: 587d7b8e367417b2b2512b5f title: Pass Arguments to Avoid External Dependence in a Function challengeType: 1 -videoUrl: '' +forumTopicId: 301234 localeTitle: 传递参数以避免函数中的外部依赖 --- ## Description -
最后一个挑战是向功能编程原则迈进了一步,但仍然缺少一些东西。我们没有改变全局变量值,但是如果没有全局变量fixedValue ,函数incrementer将无法工作。函数式编程的另一个原则是始终明确声明您的依赖项。这意味着如果函数依赖于存在的变量或对象,则将该变量或对象作为参数直接传递给函数。这个原则有几个好的结果。该函数更容易测试,您确切知道它需要什么输入,并且它不依赖于程序中的任何其他内容。当您更改,删除或添加新代码时,这可以让您更有信心。你会知道你可以或不可以改变什么,你可以看到潜在陷阱的位置。最后,无论代码的哪一部分执行,函数总是会为同一组输入生成相同的输出。
+
+上一个挑战是更接近函数式编程原则的挑战,但是仍然缺少一些东西。 +虽然我们没有改变全局变量值,但在没有全局变量fixedValue情况下,incrementer函数将不起作用。 +函数式编程的另一个原则是:总是显式声明依赖关系。如果函数依赖于一个变量或对象,那么将该变量或对象作为参数直接传递到函数中。 +这样做会有很多好处,其中一点是让函数更容易测试,因为你确切地知道参数是什么,并且这个参数也不依赖于程序中的任何其他内容。 +其次,这样做可以让你更加自信地更改,删除或添加新代码。因为你很清楚哪些是可以改的,哪些是不可以改的,这样你就知道哪里可能会有潜在的陷阱。 +最后,无论代码的哪一部分执行它,函数总是会为同一组输入生成相同的输出。 +
## Instructions -
让我们更新incrementer函数以清楚地声明其依赖关系。编写incrementer函数,使其获取参数,然后将值增加1。
+
+更新incrementer函数,明确声明其依赖项。 +编写incrementer函数,获取它的参数,然后将值增加 1。 +
## Tests
```yml tests: - - text: 您的函数incrementer不应更改fixedValue的值。 + - text: incrementer函数不能修改fixedValue的值。 testString: assert(fixedValue === 4); - - text: 您的incrementer功能应该采用参数。 + - text: incrementer函数应该接收一个参数。 testString: assert(incrementer.length === 1); - - text: 您的incrementer函数应返回一个大于fixedValue值的值。 + - text: incrementer函数应返回比fixedValue更大的值。 testString: assert(newValue === 5); ``` @@ -46,7 +56,6 @@ function incrementer () { var newValue = incrementer(fixedValue); // Should equal 5 console.log(fixedValue); // Should print 4 - ``` @@ -59,6 +68,13 @@ console.log(fixedValue); // Should print 4
```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 ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/refactor-global-variables-out-of-functions.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/refactor-global-variables-out-of-functions.chinese.md index f7f136f316..e5f26fbea2 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/refactor-global-variables-out-of-functions.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/refactor-global-variables-out-of-functions.chinese.md @@ -2,28 +2,35 @@ id: 587d7b8f367417b2b2512b60 title: Refactor Global Variables Out of Functions challengeType: 1 -videoUrl: '' -localeTitle: 重构函数的全局变量 +forumTopicId: 301235 +localeTitle: 在函数中重构全局变量 --- ## Description -
到目前为止,我们已经看到了函数式编程的两个不同原则:1)不要改变变量或对象 - 创建新的变量和对象,并在需要时从函数返回它们。 2)声明函数参数 - 函数内的任何计算仅依赖于参数,而不依赖于任何全局对象或变量。在数字中添加一个并不是很令人兴奋,但我们可以在处理数组或更复杂的对象时应用这些原则。
+
+目前为止,我们已经看到了函数式编程的两个原则: +1) 不要更改变量或对象——创建新变量和对象,并在需要时从函数返回它们。 +2) 声明函数参数——函数内的任何计算仅取决于参数,而不取决于任何全局对象或变量。 +给数字增加 1 不够刺激,我们可以在处理数组或更复杂的对象时应用这些原则。 +
## Instructions -
重构(重写)代码,以便在任一函数内部不更改全局数组bookListadd函数应该将给定的bookName添加到数组的末尾。 remove函数应该从数组中删除给定的bookName 。这两个函数都应该返回一个数组,并且应该在bookName之前添加任何新参数。
+
+重构代码,使全局数组bookList在函数内部不会被改变。add函数可以将指定的bookName增加到数组末尾。remove函数可以从数组中移除指定bookName。两个函数都返回数组,并且任何参数都应该添加到bookName前面。 +
## Tests
```yml tests: - - text: 'bookList不应该改变并且仍然相等["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"] 。' + - text: "bookList不应该改变,应等于['The Hound of the Baskervilles', 'On The Electrodynamics of Moving Bodies', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae']." 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: 'newBookList应该等于["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"] 。' + - text: "newBookList应等于['The Hound of the Baskervilles', 'On The Electrodynamics of Moving Bodies', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae', 'A Brief History of Time']." 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: 'newerBookList应该等于["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"] 。' + - text: "newerBookList应等于['The Hound of the Baskervilles', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae']." testString: assert(JSON.stringify(newerBookList) === JSON.stringify(['The Hound of the Baskervilles', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae'])); - - text: 'newestBookList应该等于["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"] 。' + - text: "newestBookList应等于['The Hound of the Baskervilles', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae', 'A Brief History of Time']." 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); - ``` @@ -81,6 +90,35 @@ console.log(bookList);
```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'); ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/remove-elements-from-an-array-using-slice-instead-of-splice.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/remove-elements-from-an-array-using-slice-instead-of-splice.chinese.md index d681a82e9b..937a161fbe 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/remove-elements-from-an-array-using-slice-instead-of-splice.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/remove-elements-from-an-array-using-slice-instead-of-splice.chinese.md @@ -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 -
使用数组时的常见模式是当您想要删除项目并保留数组的其余部分时。 JavaScript为此提供了splice方法,该方法接受索引的参数,该索引指示从何处开始删除项目,然后是要删除的项目数。如果未提供第二个参数,则默认为通过结尾删除项目。但是, splice方法会改变调用它的原始数组。这是一个例子:
var cities = [“芝加哥”,“德里”,“伊斯兰堡”,“伦敦”,“柏林”];
cities.splice(3,1); //返回“London”并从cities数组中删除它
//现在是城市[“芝加哥”,“德里”,“伊斯兰堡”,“柏林”]
正如我们在上一次挑战中看到的那样, slice方法不会改变原始数组,而是返回一个可以保存到变量中的新数组。回想一下, slice方法为索引开始和结束slice采用两个参数(结束是非包含的),并在新数组中返回这些项。使用slice方法而不是splice有助于避免任何阵列变异的副作用。
+
+使用数组时经常遇到要删除一些元素并保留数组剩余部分的情况。为此,JavaScript 提供了splice方法,它接收两个参数:从哪里开始删除项目的索引,和要删除的项目数。如果没有提供第二个参数,默认情况下是移除到结尾的元素。但splice方法会改变调用它的原始数组。举个例子: + +```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"] +``` + +正如我们在上一次挑战中看到的那样,slice方法不会改变原始数组,而是返回一个可以保存到变量中的新数组。回想一下,slice方法接收两个参数,从开始索引开始选取到结束(不包括该元素),并在新数组中返回这些元素。使用slice方法替代splice有助于避免数组变化产生的副作用。 +
## Instructions -
使用slice而不是splice重写函数nonMutatingSplice 。它应该将提供的cities数组限制为3的长度,并返回仅包含前三项的新数组。不要改变提供给函数的原始数组。
+
+用slice代替splice重写nonMutatingSplice函数。将cities数组长度限制为3,并返回一个仅包含前 3 项的新数组。 +不要改变提供给函数的原始数组。 +
## Tests
```yml tests: - - text: 您的代码应该使用slice方法。 + - text: 应该使用slice方法。 testString: assert(code.match(/\.slice/g)); - - text: 您的代码不应使用splice方法。 + - text: 不能使用splice方法。 testString: assert(!code.match(/\.splice/g)); - - text: inputCities数组不应更改。 + - text: 不能改变inputCities数组。 testString: assert(JSON.stringify(inputCities) === JSON.stringify(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])); - - text: 'nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])应该返回["Chicago", "Delhi", "Islamabad"] 。' + - text: "nonMutatingSplice(['Chicago', 'Delhi', 'Islamabad', 'London', 'Berlin'])应返回['Chicago', 'Delhi', 'Islamabad']。" 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); - ``` @@ -57,6 +69,13 @@ nonMutatingSplice(inputCities);
```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); ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/return-a-sorted-array-without-changing-the-original-array.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/return-a-sorted-array-without-changing-the-original-array.chinese.md index 311a2847a8..52c6aaeb58 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/return-a-sorted-array-without-changing-the-original-array.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/return-a-sorted-array-without-changing-the-original-array.chinese.md @@ -2,28 +2,32 @@ id: 587d7da9367417b2b2512b6a title: Return a Sorted Array Without Changing the Original Array challengeType: 1 -videoUrl: '' -localeTitle: 返回排序数组而不更改原始数组 +forumTopicId: 301237 +localeTitle: 在不更改原始数组的前提下返回排序后的数组 --- ## Description -
sort方法的一个副作用是它改变了原始数组中元素的顺序。换句话说,它将阵列变异。避免这种情况的一种方法是首先将空数组连接到正在排序的数组(记住concat返回一个新数组),然后运行sort方法。
+
+sort方法会产生改变原始数组中元素顺序的副作用。换句话说,它会改变数组的位置。避免这种情况的一种方法是先将空数组连接到正在排序的数组上(记住concat返回一个新数组),再用sort方法。 +
## Instructions -
使用nonMutatingSort函数中的sort方法按升序对数组元素进行排序。该函数应该返回一个新数组,而不是改变globalArray变量。
+
+在nonMutatingSort函数中使用sort方法对数组中的元素按升序进行排列。函数不能改变globalArray变量,应返回一个新数组。 +
## Tests
```yml tests: - - text: 您的代码应该使用sort方法。 + - text: 应该使用sort方法。 testString: assert(nonMutatingSort.toString().match(/\.sort/g)); - - text: 您的代码应使用concat方法。 + - text: 应该使用concat方法。 testString: assert(JSON.stringify(globalArray) === JSON.stringify([5, 6, 3, 2, 9])); - - text: globalArray变量不应该更改。 + - text: globalArrayvariable 应保持不变。 testString: assert(JSON.stringify(nonMutatingSort(globalArray)) === JSON.stringify([2, 3, 5, 6, 9])); - - text: 'nonMutatingSort(globalArray)应该返回[2, 3, 5, 6, 9] nonMutatingSort(globalArray) [2, 3, 5, 6, 9] 。' + - text: nonMutatingSort(globalArray)应返回[2, 3, 5, 6, 9]。 testString: assert(!nonMutatingSort.toString().match(/[23569]/g)); ``` @@ -44,7 +48,6 @@ function nonMutatingSort(arr) { // Add your code above this line } nonMutatingSort(globalArray); - ``` @@ -57,6 +60,13 @@ nonMutatingSort(globalArray);
```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); ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/return-part-of-an-array-using-the-slice-method.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/return-part-of-an-array-using-the-slice-method.chinese.md index 33aafab51a..eff567bfab 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/return-part-of-an-array-using-the-slice-method.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/return-part-of-an-array-using-the-slice-method.chinese.md @@ -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 -
slice方法返回数组的某些元素的副本。它可以采用两个参数,第一个给出切片开始位置的索引,第二个是切片结束位置的索引(并且它是非包含的)。如果未提供参数,则默认为从数组的开头到结尾开始,这是复制整个数组的简单方法。 slice方法不会改变原始数组,但会返回一个新数组。这是一个例子:
var arr = [“Cat”,“Dog”,“Tiger”,“Zebra”];
var newArray = arr.slice(1,3);
//将newArray设置为[“Dog”,“Tiger”]
+
+slice方法可以从已有数组中返回指定元素。它接受两个参数,第一个规定从何处开始选取,第二个规定从何处结束选取(不包括该元素)。如果没有传参,则默认为从数组的开头开始到结尾结束,这是复制整个数组的简单方式。slice返回一个新数组,不会修改原始数组。 +举个例子: + +```js +var arr = ["Cat", "Dog", "Tiger", "Zebra"]; +var newArray = arr.slice(1, 3); +// Sets newArray to ["Dog", "Tiger"] +``` + +
## Instructions -
在给定提供的beginSliceendSlice索引的情况下,使用sliceArray函数中的slice方法返回anim数组的一部分。该函数应返回一个数组。
+
+在sliceArray函数中使用slice方法,给出beginSliceendSlice索引,返回anim数组的一部分,这个函数应返回一个数组。 +
## Tests
```yml tests: - - text: 您的代码应该使用slice方法。 + - text: 你的代码中应使用slice方法。 testString: assert(code.match(/\.slice/g)); - - text: inputAnim变量不应该更改。 + - text: 不能改变inputAnim变量。 testString: assert(JSON.stringify(inputAnim) === JSON.stringify(["Cat", "Dog", "Tiger", "Zebra", "Ant"])); - - text: 'sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3)应该返回["Dog", "Tiger"] 。' + - text: "sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 1, 3)应返回['Dog', 'Tiger']。" testString: assert(JSON.stringify(sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3)) === JSON.stringify(["Dog", "Tiger"])); - - text: 'sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1)应返回["Cat"] 。' + - text: "sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 0, 1)应返回['Cat']。" testString: assert(JSON.stringify(sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1)) === JSON.stringify(["Cat"])); - - text: 'sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4)应返回["Dog", "Tiger", "Zebra"] 。' + - text: "sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 1, 4)应返回['Dog', 'Tiger', 'Zebra']。" 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); - ``` @@ -59,6 +70,13 @@ sliceArray(inputAnim, 1, 3);
```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); ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/sort-an-array-alphabetically-using-the-sort-method.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/sort-an-array-alphabetically-using-the-sort-method.chinese.md index 2c011c1d39..38eb5965d9 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/sort-an-array-alphabetically-using-the-sort-method.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/sort-an-array-alphabetically-using-the-sort-method.chinese.md @@ -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 -
sort方法根据回调函数对数组的元素进行sort 。例如:
function ascendingOrder(arr){
return arr.sort(function(a,b){
返回a - b;
});
}
ascendingOrder([1,5,2,3,4]);
//返回[1,2,3,4,5]

function reverseAlpha(arr){
return arr.sort(function(a,b){
返回<b;
});
}
reverseAlpha(['l','h','z','b','s']);
//返回['z','s','l','h','b']
注意:鼓励提供回调函数来指定如何对数组项进行排序。 JavaScript的默认排序方法是字符串Unicode点值,这可能会返回意外结果。
+
+sort方法可以根据回调函数对数组元素进行排序。 +举个例子: + +```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 值顺序排序,有时可能会得到意想不到的结果。所以,建议传入一个回调函数指定数组项目的排序方式,这个回调函数通常叫做 compareFunction,它根据 compareFunction 的返回值决定数组元素的排序方式: +如果两个元素 abcompareFunction(a,b) 返回一个比 0 小的值,那么 a 会在 b 的前面。 +如果两个元素 abcompareFunction(a,b) 返回一个比 0 大的值,那么 b 会在 a 的前面。 +如果两个元素 abcompareFunction(a,b) 返回等于 0 的值,那么 ab 的位置保持不变。 + +
## Instructions -
使用alphabeticalOrder函数中的sort方法alphabeticalOrder字母顺序对arr的元素进行排序。
+
+在alphabeticalOrder函数中使用sort方法对arr中的元素按照字母顺序排列。 +
## Tests
```yml tests: - - text: 您的代码应该使用sort方法。 + - text: 应该使用sort方法。 testString: assert(code.match(/\.sort/g)); - - text: 'alphabeticalOrder(["a", "d", "c", "a", "z", "g"])应返回["a", "a", "c", "d", "g", "z"] 。' + - text: "alphabeticalOrder(['a', 'd', 'c', 'a', 'z', 'g'])应返回['a', 'a', 'c', 'd', 'g', 'z']。" testString: assert(JSON.stringify(alphabeticalOrder(["a", "d", "c", "a", "z", "g"])) === JSON.stringify(["a", "a", "c", "d", "g", "z"])); - - text: 'alphabeticalOrder(["x", "h", "a", "m", "n", "m"])应返回["a", "h", "m", "m", "n", "x"] 。' + - text: "alphabeticalOrder(['x', 'h', 'a', 'm', 'n', 'm'])应返回['a', 'h', 'm', 'm', 'n', 'x']。" testString: assert(JSON.stringify(alphabeticalOrder(["x", "h", "a", "m", "n", "m"])) === JSON.stringify(["a", "h", "m", "m", "n", "x"])); - - text: 'alphabeticalOrder(["a", "a", "a", "a", "x", "t"])应返回["a", "a", "a", "a", "t", "x"] 。' + - text: "alphabeticalOrder(['a', 'a', 'a', 'a', 'x', 't'])应返回['a', 'a', 'a', 'a', 't', 'x']。" 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"]); - ``` @@ -56,6 +84,12 @@ alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
```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"]); ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/split-a-string-into-an-array-using-the-split-method.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/split-a-string-into-an-array-using-the-split-method.chinese.md index 31b8be007f..d1c8e8080d 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/split-a-string-into-an-array-using-the-split-method.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/split-a-string-into-an-array-using-the-split-method.chinese.md @@ -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 -
split方法将字符串拆分为字符串数组。它接受分隔符的参数,分隔符可以是用于分解字符串或正则表达式的字符。例如,如果分隔符是空格,则会得到一个单词数组,如果分隔符是空字符串,则会得到字符串中每个字符的数组。下面是两个用空格分隔一个字符串的例子,然后用正则表达式用数字分割另一个字符串:
var str =“Hello World”;
var bySpace = str.split(“”);
//将bySpace设置为[“Hello”,“World”]

var otherString =“How9are7you2today”;
var byDigits = otherString.split(/ \ d /);
//将byDigits设置为[“How”,“are”,“you”,“today”]
由于字符串是不可变的,因此split方法可以更轻松地使用它们。
+
+split方法用于把字符串分割成字符串数组,接收一个分隔符参数,分隔符可以是用于分解字符串或正则表达式的字符。举个例子,如果分隔符是空格,你会得到一个单词数组;如果分隔符是空字符串,你会得到一个由字符串中每个字符组成的数组。 +下面是两个用空格分隔一个字符串的例子,另一个是用数字的正则表达式分隔: + +```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"] +``` + +因为字符串是固定的,split方法可以更简单的操作它们。 +
## Instructions -
使用splitify函数内的split方法将str拆分为单词数组。该函数应该返回数组。请注意,单词并不总是用空格分隔,并且数组不应包含标点符号。
+
+在splitify函数中用split方法将str分割成单词数组,这个方法应该返回一个数组。单词不一定都是用空格分隔,所以数组中不应包含标点符号。 +
## Tests
```yml tests: - - text: 您的代码应该使用split方法。 + - text: 应该使用split方法。 testString: assert(code.match(/\.split/g)); - - text: 'splitify("Hello World,I-am code")应返回["Hello", "World", "I", "am", "code"] 。' + - text: "splitify('Hello World,I-am code')应返回['Hello', 'World', 'I', 'am', 'code']。" testString: assert(JSON.stringify(splitify("Hello World,I-am code")) === JSON.stringify(["Hello", "World", "I", "am", "code"])); - - text: 'splitify("Earth-is-our home")应该返回["Earth", "is", "our", "home"] 。' + - text: "splitify('Earth-is-our home')应返回['Earth', 'is', 'our', 'home']。" testString: assert(JSON.stringify(splitify("Earth-is-our home")) === JSON.stringify(["Earth", "is", "our", "home"])); - - text: 'splitify("This.is.a-sentence")应该返回["This", "is", "a", "sentence"] 。' + - text: "splitify('This.is.a-sentence')应返回['This', 'is', 'a', 'sentence']。" 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"); - ``` @@ -56,6 +72,11 @@ splitify("Hello World,I-am code");
```js -// solution required +function splitify(str) { + // Add your code below this line + return str.split(/\W/); + // Add your code above this line +} ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/understand-functional-programming-terminology.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/understand-functional-programming-terminology.chinese.md index 80759fb581..1b9831ea6c 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/understand-functional-programming-terminology.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/understand-functional-programming-terminology.chinese.md @@ -2,28 +2,39 @@ id: 587d7b8e367417b2b2512b5c title: Understand Functional Programming Terminology challengeType: 1 -videoUrl: '' -localeTitle: 理解功能编程术语 +forumTopicId: 301240 +localeTitle: 了解函数式编程术语 --- ## Description -
联邦通信委员会团队有一种情绪波动,现在想要两种类型的茶:绿茶和红茶。一般事实:客户情绪波动很常见。有了这些信息,我们需要重新审视上次挑战中的getTea功能,以处理各种茶叶请求。我们可以修改getTea来接受一个函数作为参数,以便能够改变它准备的茶的类型。这使得getTea更加灵活,并且在客户端请求发生变化时为程序员提供更多控制。但首先,让我们介绍一些函数术语: Callbacks函数是滑动或传递给另一个函数来决定函数调用的函数。您可能已经看到它们传递给其他方法,例如在filter ,回调函数告诉JavaScript如何过滤数组的标准。可以分配给变量,传递到另一个函数或从其他函数返回的函数就像任何其他正常值一样,称为first class函数。在JavaScript中,所有函数都是first class函数。将函数作为参数或将函数作为返回值返回的函数称为higher order函数。当函数传递给另一个函数或从另一个函数返回时,那些传入或返回的函数可以称为lambda
+
+FCC 团队需求有变更,现在想要两种茶:绿茶(green tea)和红茶(black tea)。事实证明,用户需求变更是很常见的。 +基于以上信息,我们需要重构上一节挑战中的getTea函数来处理多种茶的请求。我们可以修改getTea接受一个函数作为参数,使它能够修改茶的类型。这让getTea更灵活,也使需求变更时为程序员提供更多控制权。 +首先,我们将介绍一些术语: +Callbacks是被传递到另一个函数中调用的函数。你应该已经在其他函数中看过这个写法,例如在filter中,回调函数告诉 JavaScript 以什么规则过滤数组。 +函数就像其他正常值一样,可以赋值给变量、传递给另一个函数,或从其它函数返回,这种函数叫做头等函数。在 JavaScript 中,所有函数都是头等函数。 +将函数为参数或返回值的函数叫做高阶函数。 +当函数传递给另一个函数或从另一个函数返回时,那些传入或返回的函数可以叫做lambda。 +
## Instructions -
准备27杯绿茶和13杯红茶,分别储存在tea4GreenTeamFCCtea4BlackTeamFCC变量中。请注意, getTea函数已被修改,因此它现在将函数作为第一个参数。注意:数据(茶杯数量)作为最后一个参数提供。我们将在后面的课程中对此进行更多讨论。
+
+准备 27 杯绿茶和 13 杯红茶,分别存入tea4GreenTeamFCCtea4BlackTeamFCC变量。请注意,getTea函数已经变了,现在它接收一个函数作为第一个参数。 +注意:数据(茶的数量)作为最后一个参数。我们将在后面的课程中对此进行更多讨论。 +
## Tests
```yml tests: - - text: tea4GreenTeamFCC变量应该为团队提供27杯绿茶。 + - text: tea4GreenTeamFCC变量应存有为团队准备的 27 杯茶。 testString: assert(tea4GreenTeamFCC.length === 27); - - text: tea4GreenTeamFCC变量应该拿着一杯绿茶。 + - text: tea4GreenTeamFCC变量应存有绿茶。 testString: assert(tea4GreenTeamFCC[0] === 'greenTea'); - - text: tea4BlackTeamFCC变量应该可以容纳13杯红茶。 + - text: tea4BlackTeamFCC变量应存有 13 杯红茶。 testString: assert(tea4BlackTeamFCC.length === 13); - - text: tea4BlackTeamFCC变量应该拿着一杯红茶。 + - text: tea4BlackTeamFCC变量应存有红茶。 testString: assert(tea4BlackTeamFCC[0] === 'blackTea'); ``` @@ -76,7 +87,6 @@ console.log( tea4GreenTeamFCC, tea4BlackTeamFCC ); - ``` @@ -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); ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/understand-the-hazards-of-using-imperative-code.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/understand-the-hazards-of-using-imperative-code.chinese.md index c74c102f44..bb1bd38cc2 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/understand-the-hazards-of-using-imperative-code.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/understand-the-hazards-of-using-imperative-code.chinese.md @@ -2,15 +2,30 @@ id: 587d7b8e367417b2b2512b5d title: Understand the Hazards of Using Imperative Code challengeType: 1 -videoUrl: '' -localeTitle: 了解使用命令代码的危害 +forumTopicId: 301241 +localeTitle: 了解使用命令式编程的危害 --- ## Description -
功能编程是一个好习惯。它使您的代码易于管理,并使您免于偷偷摸摸的错误。但在我们到达那里之前,让我们看一下编程的必要方法,以突出您可能遇到的问题。在英语(和许多其他语言)中,命令式时态用于给出命令。类似地,编程中的命令式是为计算机提供一组语句来执行任务。通常,语句会更改程序的状态,例如更新全局变量。一个典型的例子是编写一个for循环,它给出了迭代数组索引的精确方向。相反,函数式编程是声明式编程的一种形式。通过调用方法或函数告诉计算机您想要做什么。 JavaScript提供了许多处理常见任务的预定义方法,因此您无需写出计算机应如何执行它们。例如,您可以调用map方法来处理迭代数组的细节,而不是使用上面提到的for循环。这有助于避免语义错误,例如调试部分中介绍的“Off By One Errors”。请考虑以下情况:您正在浏览器中浏览Web,并希望跟踪已打开的选项卡。让我们尝试使用一些简单的面向对象的代码对此进行建模。 Window对象由选项卡组成,您通常打开多个Window。每个Window对象中每个开放站点的标题都保存在一个数组中。在浏览器中工作(打开新选项卡,合并窗口和关闭选项卡)后,您需要打印仍处于打开状态的选项卡。从数组中删除已关闭的选项卡,并将新选项卡(为简单起见)添加到其末尾。代码编辑器显示了此功能的实现,其中包含tabOpen()tabClose()join()函数。数组tabs是Window对象的一部分,用于存储打开页面的名称。

说明

在编辑器中运行代码。它使用的方法在程序中有副作用,导致输出错误。打开标签的最终列表应该是['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']但输出会略有不同。完成代码并查看是否可以找出问题,然后进入下一个挑战以了解更多信息。

+
+函数式编程是一种好习惯,它能让代码管理更简单,不受隐藏 bug 影响。在我们开始函数式编程之前,为了更好的突显可能遇到的问题,我们先看看命令式编程。 +类似在英语(和许多其他语言)中,命令式时态用于给出命令,编程中的命令式是给计算机一组语句来执行任务。 +这些语句通常会改变程序的状态,例如更新全局变量,典型的例子就是写一个 for 循环,它给出了迭代数组索引的精确方向。 +相反,函数式编程是声明式编程的一种形式,通过调用方法或函数来告诉计算机要做什么。 +JavaScript 提供了许多处理常见任务的方法,所以你无需写出计算机应如何执行它们。例如,你可以用 map 函数替代上面提到的 for 循环来处理数组迭代。这有助于避免语义错误,如调试章节介绍的"Off By One Errors"。 +考虑这样的场景:你正在浏览器中浏览网页,并想操作你打开的标签。下面我们来试试用面向对象的思路来描述这种情景。 +窗口对象由选项卡组成,通常会打开多个窗口。窗口对象中每个打开网站的标题都保存在一个数组中。在对浏览器进行了如打开新标签、合并窗口、关闭标签之类的操作后,你需要输出所有打开的标签。关掉的标签将从数组中删除,新打开的标签(为简单起见)则添加到数组的末尾。 +代码编辑器中显示了此功能的实现,其中包含 tabOpen()tabClose(),和 join() 函数。tabs数组是窗口对象的一部分用于储存打开页面的名称。 + + +
+ ## Instructions -
+
+在编辑器中运行代码。它使用了有副作用的方法,导致输出错误。打开标签的最终列表应该是 ['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab'] 但输出会略有不同。 + +修改 Window.prototype.tabClose 使其删除正确的标签。
## Tests @@ -18,7 +33,7 @@ localeTitle: 了解使用命令代码的危害 ```yml tests: - - text: 继续前进以了解错误。 + - text: finalTabs.tabs 应该是 ['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab'] 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); +``` + + + + + +
+ +## 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); - ``` - - - - -
- -## Solution -
- -```js -// solution required -```
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-problem.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-problem.chinese.md new file mode 100644 index 0000000000..99f11d9642 --- /dev/null +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-problem.chinese.md @@ -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 +
+已经接触了高阶函数如 map()filter()reduce()的使用,是时候用它们来完成一些复杂的挑战了。 +
+ +## Instructions +
+已经定义了一个函数 squareList。任意组合 map()filter()reduce() 来完成函数,满足以下条件,当传入实数数组(如,[-3, 4.8, 5, 3, -3.2])时,返回包含正整数的平方的新数组。 +注意: 函数不应该包含任何形式的 for 或者 while 循环或者 forEach() 函数。 +
+ +## Tests +
+ +```yml +tests: + - text: squareList 应该是一个 function。 + testString: assert.typeOf(squareList, 'function'), 'squareList should be a function'; + - text: 不应该使用 for 或者 while 循环或者 forEach。 + testString: assert(!removeJSComments(code).match(/for|while|forEach/g)); + - text: 应该使用 mapfilter 或者 reduce。 + testString: assert(removeJSComments(code).match(/\.(map|filter|reduce)\s*\(/g)); + - text: 函数应该返回 array。 + testString: assert(Array.isArray(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]))); + - text: squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]) 应该返回 [16, 1764, 36]。 + testString: assert.deepStrictEqual(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]), [16, 1764, 36]); + - text: squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3]) 应该返回 [9, 100, 49]。 + testString: assert.deepStrictEqual(squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3]), [9, 100, 49]); +``` + +
+ +## Challenge 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); +``` + +
+ +
+ +```js +const removeJSComments = str => str.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, ''); +``` + +
+ +
+ +## 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; +}; +``` + +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria.chinese.md index 24384b031c..6a0628ce9d 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria.chinese.md @@ -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 -
every方法都使用数组来检查每个元素是否通过了特定的测试。它返回一个布尔值 - 如果所有值都满足条件,则返回true否则返回false 。例如,以下代码将检查numbers数组中的每个元素是否小于10:
var numbers = [1,5,8,0,10,11];
numbers.every(function(currentValue){
return currentValue <10;
});
//返回false
+
+every方法用于检测数组中所有元素是否都符合指定条件。如果所有元素满足条件,返回布尔值true,反之返回false。 +举个例子,下面的代码检测数组numbers的所有元素是否都小于 10: + +```js +var numbers = [1, 5, 8, 0, 10, 11]; +numbers.every(function(currentValue) { + return currentValue < 10; +}); +// Returns false +``` + +
## Instructions -
使用checkPositive函数中的every方法检查arr每个元素是否为正数。该函数应返回一个布尔值。
+
+在checkPositive函数中使用every方法检查arr中是否所有元素都是正数,函数应返回一个布尔值。 +
## Tests
```yml tests: - - text: 您的代码应该使用every方法。 + - text: 应使用every方法。 testString: assert(code.match(/\.every/g)); - - text: 'checkPositive([1, 2, 3, -4, 5])应该返回false 。' + - text: checkPositive([1, 2, 3, -4, 5])应返回false。 testString: assert.isFalse(checkPositive([1, 2, 3, -4, 5])); - - text: 'checkPositive([1, 2, 3, 4, 5])应该返回true 。' + - text: checkPositive([1, 2, 3, 4, 5])应返回true。 testString: assert.isTrue(checkPositive([1, 2, 3, 4, 5])); - - text: 'checkPositive([1, -2, 3, -4, 5])应该返回false 。' + - text: checkPositive([1, -2, 3, -4, 5])应返回false。 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]); - ``` @@ -56,6 +69,12 @@ checkPositive([1, 2, 3, -4, 5]);
```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]); ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-filter-method-to-extract-data-from-an-array.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-filter-method-to-extract-data-from-an-array.chinese.md index 22a0bb5094..c5889aa5f3 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-filter-method-to-extract-data-from-an-array.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-filter-method-to-extract-data-from-an-array.chinese.md @@ -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 -
另一个有用的数组函数是Array.prototype.filter() ,或者只是filter()filter方法返回一个新数组,该数组最多与原始数组一样长,但通常只有较少的项。 Filter不会像map一样改变原始数组。它需要一个回调函数,它将回调内的逻辑应用于数组的每个元素。如果元素根据回调函数中的条件返回true,则它将包含在新数组中。
+
+另一个有用的数组方法是filter()(即Array.prototype.filter())。filter方法会返回一个长度不大于原始数组的新数组。 +和map一样,Filter不会改变原始数组,它接收一个回调函数,将回调内的逻辑应用于数组的每个元素。新数组包含根据回调函数内条件返回 true 的元素。 +回调函数接收三个参数。第一个参数是当前正在被处理的元素,第二个参数是元素的索引,第三个参数是在其上调用 filter 方法的数组。 +看下在 users 上使用 filter 方法的例子,返回了一个新数组包含了 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 } ] +``` + +
## Instructions -
变量watchList对象,其中包含有关多部电影的信息。使用filtermap的组合返回仅具有titlerating键的新对象数组,但imdbRating大于或等于8.0。请注意,评级值在对象中保存为字符串,您可能希望将它们转换为数字以对它们执行数学运算。
+
+watchList是包含一些电影信息的对象。结合filtermap返回一个只包含titlerating属性的新数组,并且imdbRating值大于或等于 8.0。请注意,评级值在对象中保存为字符串,你可能需要将它转换成数字来执行运算。 +
## Tests
```yml tests: - - text: watchList变量不应该更改。 + - text: watchList应保持不变。 testString: assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron"); - - text: 您的代码应该使用filter方法。 + - text: 应使用filter方法。 testString: assert(code.match(/\.filter/g)); - - text: 您的代码不应使用for循环。 - testString: assert(!code.match(/for\s*?\([\s\S]*?\)/g)); - - text: 'filteredList应该等于[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}] 。' + - text: 不能使用for循环。 + testString: assert(!code.match(/for\s*?\(.+?\)/g)); + - text: 'filteredList应等于[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]。' 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); - ``` @@ -170,6 +188,123 @@ console.log(filteredList);
```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 ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-map-method-to-extract-data-from-an-array.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-map-method-to-extract-data-from-an-array.chinese.md index 8f6112aab7..ad4c95a2ab 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-map-method-to-extract-data-from-an-array.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-map-method-to-extract-data-from-an-array.chinese.md @@ -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 -
到目前为止,我们已经学会使用纯函数来避免程序中的副作用。此外,我们已经看到函数的值仅取决于其输入参数。这仅仅是个开始。顾名思义,函数式编程以函数理论为中心。能够将它们作为参数传递给其他函数,并从另一个函数返回一个函数是有意义的。函数被认为是JavaScript中的First Class Objects ,这意味着它们可以像任何其他对象一样使用。它们可以保存在变量中,存储在对象中,也可以作为函数参数传递。让我们从一些简单的数组函数开始,这些函数是数组对象原型的方法。在本练习中,我们将查看Array.prototype.map() ,或更简单的map 。请记住, map方法是一种迭代数组中每个项目的方法。在将回调函数应用于每个元素之后,它会创建一个新数组(不更改原始数组)。
+
+目前为止,我们已经学会了使用纯函数来避免程序中的副作用。此外,我们已经看到函数的值仅取决于其输入参数。 +这仅仅是个开始。顾名思义,函数式编程以函数理论为中心。 +能够将它们作为参数传递给其他函数,和从另一个函数返回一个函数是有意义的。函数在 JavaScript 中被视为First Class Objects,它们可以像任何其他对象一样使用。它们可以保存在变量中,存储在对象中,也可以作为函数参数传递。 +让我们从一些简单的数组函数开始,这些函数是数组对象原型上的方法。在本练习中,我们来了解下数组的map方法(即Array.prototype.map())。 +请记住,map方法是迭代数组中每一项的方式之一。在对每个元素应用回调函数后,它会创建一个新数组(不改变原来的数组)。 +当调用回调函数时,传入了三个参数。第一个参数是当前正在处理的数组项,第二个参数是当前数组项的索引值,第三个参数是在其上调用 map 方法的数组。 +看下在 users 上使用 map 方法的例子,返回了一个新数组只包含了用户的名字。为了简化,例子里只使用了回调函数的第一个参数。 + +```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' ] +``` + +
## Instructions -
watchList数组保存包含多部电影信息的对象。使用mapwatchList提取标题和评级,并将新数组保存在rating变量中。编辑器中的代码当前使用for循环来执行此操作,将循环功能替换为map表达式。
+
+watchList数组保存了包含一些电影信息的对象。使用mapwatchList中提取标题(title)和评分(rating),并将新数组保存在rating变量里。目前编辑器中的代码是使用for循环实现,使用map表达式替换循环功能。 +
## Tests
```yml tests: - - text: watchList变量不应该更改。 + - text: watchList不能被改变 testString: assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron"); - - text: 您的代码不应使用for循环。 - testString: assert(!removeJSComments(code).match(/for\s*?\([\s\S]*?\)/)); - - text: 您的代码应该使用map方法。 + - text: 你的代码不能使用for循环。 + testString: assert(!removeJSComments(code).match(/for\s*?\(.*?\)/)); + - text: 你的代码应使用map方法。 testString: assert(code.match(/\.map/g)); - - text: 'rating应该等于[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}] 。' - 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: 'rating应等于[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}].' + 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)); ``` +### After Test +
+```js +const removeJSComments = str => str.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, ''); +``` + +
@@ -173,6 +201,126 @@ console.log(rating);
```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"] + } +}); ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-reduce-method-to-analyze-data.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-reduce-method-to-analyze-data.chinese.md index de5db35d72..6092a7a4d9 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-reduce-method-to-analyze-data.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-reduce-method-to-analyze-data.chinese.md @@ -2,29 +2,73 @@ id: 587d7da9367417b2b2512b68 title: Use the reduce Method to Analyze Data challengeType: 1 -videoUrl: '' -localeTitle: 使用reduce方法分析数据 +forumTopicId: 301313 +localeTitle: 使用 reduce 方法分析数据 --- ## Description -
Array.prototype.reduce()或简称reduce()是JavaScript中所有数组操作中最常见的。您可以使用reduce方法解决几乎任何数组处理问题。 filtermap方法不是这种情况,因为它们不允许阵列的两个不同元素之间的交互。例如,如果要比较数组的元素或将它们添加到一起,则filtermap无法处理它。 reduce方法允许更一般的数组处理形式,并且可以显示filtermap都可以作为reduce的特殊应用派生。但是,在我们到达之前,让我们先练习使用reduce
+
+ +reduce()(即Array.prototype.reduce()),是 JavaScript 所有数组操作中最常用的方法。几乎可以用reduce方法解决所有数组处理问题。 + +reduce方法是处理数组更通用的方式,而且filtermap方法都可以当作是reduce的特殊实现。 + reduce 方法遍历数组中的每个项目并返回单个值(即字符串、数字、对象、数组)。 这是通过在每次迭代中调用一个回调函数来实现的。 + +回调函数接受四个参数。第一个参数称为叠加器,它是上一次迭代中回调函数的返回值,第二个参数是当前正在处理的数组元素,第三个参数是该参数的索引,第四个参数是在其上调用 reduce 方法的数组。 + +除了回调函数,reduce 还有一个额外的参数做为叠加器的初始值。如果没有第二个参数,会跳过第一次迭代,第二次迭代给叠加器传入数组的第一个元素。 + +见下面的例子,给 users 数组使用 reduce 方法,返回所有用户数组的和。为了简化,例子仅使用了回调函数的第一个参数和第二个参数。 + +```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 } +``` + +
## Instructions -
变量watchList对象,其中包含有关多部电影的信息。使用reduce查找Christopher Nolan指导的电影的平均IMDB评级。回想一下先前的挑战,如何filter数据并将数据map到您需要的地方。您可能需要创建其他变量,但将最终平均值保存到变量averageRating 。请注意,评级值在对象中保存为字符串,在用于任何数学运算之前需要转换为数字。
+
+watchList变量中包含一组存有多部电影信息对象。使用reduce查找由 Christopher Nolan 导演的电影的 IMDB 评级平均值。回想一下之前的挑战,如何filter数据,以及使用map来获取你想要的数据。你可能需要创建一些变量,但是请将最后的平均值保存到averageRating变量中。请注意,评级在对象中是字符串,需要将其转换为数字再用于数学运算。 +
## Tests
```yml tests: - - text: watchList变量不应该更改。 - testString: 'assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron", "The watchList variable should not change.");' - - text: 您的代码应使用reduce方法。 - testString: 'assert(code.match(/\.reduce/g), "Your code should use the reduce method.");' - - text: averageRating应该等于8.675。 - testString: 'assert(averageRating == 8.675, "The averageRating should equal 8.675.");' - - text: 您的代码不应使用for循环。 - testString: 'assert(!code.match(/for\s*?\(.*\)/g), "Your code should not use a for loop.");' + - text: watchList应保持不变。 + testString: assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron"); + - text: 应该使用reduce方法。 + testString: assert(code.match(/\.reduce/g)); + - text: TheaverageRating应等于 8.675。 + testString: assert(getRating(watchList) === 8.675); + - text: 不能使用for循环。 + testString: assert(!code.match(/for\s*?\(.*\)/g)); + - text: 在修改 watchList 对象后应该返回正确的输出。 + 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)); ``` @@ -170,6 +215,129 @@ console.log(averageRating);
```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; +} + ``` +
diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria.chinese.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria.chinese.md index 06eed8fa19..422e3161af 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria.chinese.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria.chinese.md @@ -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 -
some方法适用于数组,以检查是否有任何元素通过了特定的测试。它返回一个布尔值 - 如果任何值满足条件,则返回true否则返回false 。例如,以下代码将检查numbers数组中的任何元素是否小于10:
var number = [10,50,8,220,110,11];
numbers.some(function(currentValue){
return currentValue <10;
});
//返回true
+
+some方法用于检测数组中任何元素是否满足指定条件。如果有一个元素满足条件,返回布尔值true,反之返回false。 +举个例子,下面的代码检测数组numbers中是否有元素小于10: + +```js +var numbers = [10, 50, 8, 220, 110, 11]; +numbers.some(function(currentValue) { + return currentValue < 10; +}); +// Returns true +``` + +
## Instructions -
使用checkPositive函数中的some方法检查arr任何元素是否为正数。该函数应返回一个布尔值。
+
+在checkPositive函数值中使用some检查arr中是否有元素为正数,函数应返回一个布尔值。 +
## Tests
```yml tests: - - text: 您的代码应该使用some方法。 + - text: 应该使用somemethod. testString: assert(code.match(/\.some/g)); - - text: 'checkPositive([1, 2, 3, -4, 5])应该返回true 。' + - text: checkPositive([1, 2, 3, -4, 5])应返回true。 testString: assert(checkPositive([1, 2, 3, -4, 5])); - - text: 'checkPositive([1, 2, 3, 4, 5])应该返回true 。' + - text: checkPositive([1, 2, 3, 4, 5])应返回true。 testString: assert(checkPositive([1, 2, 3, 4, 5])); - - text: 'checkPositive([-1, -2, -3, -4, -5])应该返回false 。' + - text: checkPositive([-1, -2, -3, -4, -5])应返回false。 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]); - ``` @@ -56,6 +69,12 @@ checkPositive([1, 2, 3, -4, 5]);
```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]); ``` +