concat
方法作为一种将数组组合成新数组而不改变原始数组的方法。将concat
与push
方法进行比较。 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
方法可以将新项目添加到数组末尾,而不产生任何变化。
+nonMutatingPush
函数,使其使用concat
将newItem
添加到original
结尾而不是push
。该函数应返回一个数组。 nonMutatingPush
函数,用concat
替代push
将newItem
添加到original
末尾,该函数应返回一个数组。
+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);
reduce
,这是一种用于将问题简化为更简单形式的强大方法。从计算平均值到排序,可以通过应用它来实现任何阵列操作。回想一下map
和filter
是reduce
特例。让我们结合我们学到的东西来解决实际问题。许多内容管理站点(CMS)将帖子的标题添加到URL的一部分以用于简单的书签目的。例如,如果您编写一个标题为“Stop Using Reduce”的Medium帖子,则URL可能会包含某种形式的标题字符串(“... / stop-using-reduce”)。您可能已经在freeCodeCamp网站上注意到了这一点。 reduce
方法,从计算平均值到排序,任何数组操作都可以用它来实现。回想一下,map
和filter
方法都是reduce
的特殊实现。
+让我们把学到的知识结合起来解决一个实际问题。
+许多内容管理站点(CMS)为了让添加书签更简单,会将帖子的标题添加到 URL 上。举个例子,如果你写了一篇标题为 "Stop Using Reduce" 的帖子,URL很可能会包含标题字符串的某种形式 (如:".../stop-using-reduce"),你可能已经在 freeCodeCamp 网站上注意到了这一点。
+urlSlug
函数,以便转换字符串title
并返回URL的连字符版本。您可以使用本节中介绍的任何方法,也不要使用replace
。以下是要求:输入是一个带空格和标题字的字符串输出是一个字符串,单词之间的空格用连字符替换( -
)输出应该是所有低位字母输出不应该有任何空格urlSlug
函数,将字符串title
转换成带有连字符号的 URL。您可以使用本节中介绍的任何方法,但不要用replace
方法。以下是本次挑战的要求:
+输入包含空格和标题大小写单词的字符串
+输出字符串,单词之间的空格用连字符(-
)替换
+输出应该是小写字母
+输出不应有任何空格
+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"
tabClose()
函数中的splice
调用。不幸的是, splice
更改了它所调用的原始数组,因此对它的第二次调用使用了一个修改过的数组,并给出了意想不到的结果。这是一个更大模式的一个小例子 - 你在一个变量,数组或一个对象上调用一个函数,该函数改变了对象中的变量或其他东西。函数式编程的核心原则之一是不改变事物。变化导致错误。知道你的函数不会改变任何东西,包括函数参数或任何全局变量,更容易防止错误。前面的例子没有任何复杂的操作,但是splice
方法改变了原始数组,并导致了一个bug。回想一下,在函数式编程中,改变或改变事物称为mutation
,结果称为side effect
。理想情况下,函数应该是pure function
,这意味着它不会产生任何副作用。让我们尝试掌握这门学科,不要改变代码中的任何变量或对象。 tabClose()
函数里的splice
。不幸的是,splice
修改了调用它的原始数组,所以第二次调用它时是基于修改后的数组,才给出了意料之外的结果。
+这是一个小例子,还有更广义的定义——在变量,数组或对象上调用一个函数,这个函数会改变对象中的变量或其他东西。
+函数式编程的核心原则之一是不改变任何东西。变化会导致错误。如果一个函数不改变传入的参数、全局变量等数据,那么它造成问题的可能性就会小很多。
+前面的例子没有任何复杂的操作,但是splice
方法改变了原始数组,导致 bug 产生。
+回想一下,在函数式编程中,改变或变更叫做mutation
,这种改变的结果叫做“副作用”(side effect
)。理想情况下,函数应该是不会产生任何副作用的纯函数
。
+让我们尝试掌握这个原则:不要改变代码中的任何变量或对象。
+incrementer
的代码,使其返回全局变量fixedValue
的值增加1。 incrementer
函数的代码,使其返回全局变量fixedValue
的值增加 1。
+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
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"
+```
+
+sentensify
函数内的join
方法(以及其他方法)从字符串str
的单词创建一个句子。该函数应返回一个字符串。例如,“我喜欢星球大战”将被转换为“我喜欢星球大战”。对于此挑战,请勿使用replace
方法。 sentensify
内用join
方法(及其他方法)用字符串str
中的单词造句,这个函数应返回一个字符串。举个例子,"I-like-Star-Wars" 会被转换成 "I like Star Wars"。在此挑战中请勿使用replace
方法。
+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");
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]
+```
+
+nonMutatingConcat
函数中的concat
方法attach
到original
的结尾。该函数应返回连接数组。 nonMutatingConcat
函数里使用concat
,将attach
拼接到original
尾部,返回拼接后的数组。
+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);
Array.prototype.map()
或之前简单地map()
所看到的那样, map
方法返回一个与调用它的长度相同的数组。它也不会改变原始数组,只要它的回调函数不会。换句话说, map
是一个纯函数,它的输出完全取决于它的输入。另外,它需要另一个函数作为其参数。它会教我们很多关于map
的尝试实现它的一个版本,它的行为与带有for
循环或Array.prototype.forEach()
的Array.prototype.map()
完全相同。注意:允许纯函数改变在其范围内定义的局部变量,但是,最好也避免使用它。 map
方法(即Array.prototype.map()
)返回一个与调用它的数组长度相同的数组。只要它的回调函数不改变原始数组,它就不会改变原始数组。
+换句话说,map
是一个纯函数,它的输出仅取决于输入的数组和作为参数传入的回调函数。
+为了加深对map
方法的理解,现在我们来用for
或Array.prototype.forEach()
自己实现一下这个方法。
+注意:纯函数可以改变其作用域内定义的局部变量,但我们最好不要这样做。
+Array.prototype.myMap()
,其行为应与Array.prototype.map()
完全相同。您可以使用for
循环或forEach
方法。 Array.prototype.map()
一样的Array.prototype.myMap()
。你可以用for
循环或者forEach
方法。
+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){
Array.prototype.filter()
完全相同的版本,它会教会我们很多关于filter
方法的内容。它可以使用for
循环或Array.prototype.forEach()
。注意:允许纯函数改变在其范围内定义的局部变量,但是,最好也避免使用它。 filter
的理解,现在我们来自己实现一下Array.prototype.filter()
方法。可以用for
循环或Array.prototype.forEach()
。
+请注意:纯函数可以改变其作用域内定义的局部变量,但我们最好不要这样做。
+Array.prototype.myFilter()
,其行为应与Array.prototype.filter()
完全相同。您可以使用for
循环或Array.prototype.forEach()
方法。 Array.prototype.filter()
功能一样的Array.prototype.myFilter()
方法。你可以用for
循环或Array.prototype.forEach()
方法。
+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){
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
+```
+
+add
函数的主体,以便使用currying来添加参数x
, y
和z
。 add
函数主体部分,用柯里化添加参数x
,y
和z
.
+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);
INPUT -> PROCESS -> OUTPUT
功能编程是关于:1)隔离函数 - 不依赖于程序的状态,其中包括可能发生变化的全局变量2)纯函数 - 相同的输入总是给出相同的输出3)副作用有限的功能 - 对功能外部程序状态的任何改变或突变都要仔细控制INPUT -> PROCESS -> OUTPUT
+函数式编程:
+1)功能独立——不依赖于程序的状态(比如可能发生变化的全局变量);
+2)纯函数——同一个输入永远能得到同一个输出;
+3)有限的副作用——可以严格地限制函数外部对状态的更改。
+prepareTea
和getTea
函数。调用getTea
函数为团队获取40杯茶,并将它们存储在tea4TeamFCC
变量中。 prepareTea
和getTea
函数。调用getTea
函数为团队准备 40 杯茶,并将它们存储在tea4TeamFCC
变量里。
+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);
```
+
fixedValue
,函数incrementer
将无法工作。函数式编程的另一个原则是始终明确声明您的依赖项。这意味着如果函数依赖于存在的变量或对象,则将该变量或对象作为参数直接传递给函数。这个原则有几个好的结果。该函数更容易测试,您确切知道它需要什么输入,并且它不依赖于程序中的任何其他内容。当您更改,删除或添加新代码时,这可以让您更有信心。你会知道你可以或不可以改变什么,你可以看到潜在陷阱的位置。最后,无论代码的哪一部分执行,函数总是会为同一组输入生成相同的输出。 fixedValue
情况下,incrementer
函数将不起作用。
+函数式编程的另一个原则是:总是显式声明依赖关系。如果函数依赖于一个变量或对象,那么将该变量或对象作为参数直接传递到函数中。
+这样做会有很多好处,其中一点是让函数更容易测试,因为你确切地知道参数是什么,并且这个参数也不依赖于程序中的任何其他内容。
+其次,这样做可以让你更加自信地更改,删除或添加新代码。因为你很清楚哪些是可以改的,哪些是不可以改的,这样你就知道哪里可能会有潜在的陷阱。
+最后,无论代码的哪一部分执行它,函数总是会为同一组输入生成相同的输出。
+incrementer
函数以清楚地声明其依赖关系。编写incrementer
函数,使其获取参数,然后将值增加1。 incrementer
函数,明确声明其依赖项。
+编写incrementer
函数,获取它的参数,然后将值增加 1。
+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
bookList
。 add
函数应该将给定的bookName
添加到数组的末尾。 remove
函数应该从数组中删除给定的bookName
。这两个函数都应该返回一个数组,并且应该在bookName
之前添加任何新参数。 bookList
在函数内部不会被改变。add
函数可以将指定的bookName
增加到数组末尾。remove
函数可以从数组中移除指定bookName
。两个函数都返回数组,并且任何参数都应该添加到bookName
前面。
+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);
splice
方法,该方法接受索引的参数,该索引指示从何处开始删除项目,然后是要删除的项目数。如果未提供第二个参数,则默认为通过结尾删除项目。但是, splice
方法会改变调用它的原始数组。这是一个例子: var cities = [“芝加哥”,“德里”,“伊斯兰堡”,“伦敦”,“柏林”];正如我们在上一次挑战中看到的那样,
cities.splice(3,1); //返回“London”并从cities数组中删除它
//现在是城市[“芝加哥”,“德里”,“伊斯兰堡”,“柏林”]
slice
方法不会改变原始数组,而是返回一个可以保存到变量中的新数组。回想一下, slice
方法为索引开始和结束slice
采用两个参数(结束是非包含的),并在新数组中返回这些项。使用slice
方法而不是splice
有助于避免任何阵列变异的副作用。 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
有助于避免数组变化产生的副作用。
+slice
而不是splice
重写函数nonMutatingSplice
。它应该将提供的cities
数组限制为3的长度,并返回仅包含前三项的新数组。不要改变提供给函数的原始数组。 slice
代替splice
重写nonMutatingSplice
函数。将cities
数组长度限制为3,并返回一个仅包含前 3 项的新数组。
+不要改变提供给函数的原始数组。
+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);
sort
方法的一个副作用是它改变了原始数组中元素的顺序。换句话说,它将阵列变异。避免这种情况的一种方法是首先将空数组连接到正在排序的数组(记住concat
返回一个新数组),然后运行sort
方法。 sort
方法会产生改变原始数组中元素顺序的副作用。换句话说,它会改变数组的位置。避免这种情况的一种方法是先将空数组连接到正在排序的数组上(记住concat
返回一个新数组),再用sort
方法。
+nonMutatingSort
函数中的sort
方法按升序对数组元素进行排序。该函数应该返回一个新数组,而不是改变globalArray
变量。 nonMutatingSort
函数中使用sort
方法对数组中的元素按升序进行排列。函数不能改变globalArray
变量,应返回一个新数组。
+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: globalArray
variable 应保持不变。
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);
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"]
+```
+
+beginSlice
和endSlice
索引的情况下,使用sliceArray
函数中的slice
方法返回anim
数组的一部分。该函数应返回一个数组。 sliceArray
函数中使用slice
方法,给出beginSlice
和endSlice
索引,返回anim
数组的一部分,这个函数应返回一个数组。
+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);
sort
方法根据回调函数对数组的元素进行sort
。例如: function ascendingOrder(arr){注意:鼓励提供回调函数来指定如何对数组项进行排序。 JavaScript的默认排序方法是字符串Unicode点值,这可能会返回意外结果。
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']
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
的返回值决定数组元素的排序方式:
+如果两个元素 a
和 b
,compareFunction(a,b)
返回一个比 0 小的值,那么 a
会在 b
的前面。
+如果两个元素 a
和 b
,compareFunction(a,b)
返回一个比 0 大的值,那么 b
会在 a
的前面。
+如果两个元素 a
和 b
,compareFunction(a,b)
返回等于 0 的值,那么 a
和 b
的位置保持不变。
+
+alphabeticalOrder
函数中的sort
方法alphabeticalOrder
字母顺序对arr
的元素进行排序。 alphabeticalOrder
函数中使用sort
方法对arr
中的元素按照字母顺序排列。
+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"]);
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
方法可以更简单的操作它们。
+splitify
函数内的split
方法将str
拆分为单词数组。该函数应该返回数组。请注意,单词并不总是用空格分隔,并且数组不应包含标点符号。 splitify
函数中用split
方法将str
分割成单词数组,这个方法应该返回一个数组。单词不一定都是用空格分隔,所以数组中不应包含标点符号。
+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");
getTea
功能,以处理各种茶叶请求。我们可以修改getTea
来接受一个函数作为参数,以便能够改变它准备的茶的类型。这使得getTea
更加灵活,并且在客户端请求发生变化时为程序员提供更多控制。但首先,让我们介绍一些函数术语: Callbacks
函数是滑动或传递给另一个函数来决定函数调用的函数。您可能已经看到它们传递给其他方法,例如在filter
,回调函数告诉JavaScript如何过滤数组的标准。可以分配给变量,传递到另一个函数或从其他函数返回的函数就像任何其他正常值一样,称为first class
函数。在JavaScript中,所有函数都是first class
函数。将函数作为参数或将函数作为返回值返回的函数称为higher order
函数。当函数传递给另一个函数或从另一个函数返回时,那些传入或返回的函数可以称为lambda
。 getTea
函数来处理多种茶的请求。我们可以修改getTea
接受一个函数作为参数,使它能够修改茶的类型。这让getTea
更灵活,也使需求变更时为程序员提供更多控制权。
+首先,我们将介绍一些术语:
+Callbacks
是被传递到另一个函数中调用的函数。你应该已经在其他函数中看过这个写法,例如在filter
中,回调函数告诉 JavaScript 以什么规则过滤数组。
+函数就像其他正常值一样,可以赋值给变量、传递给另一个函数,或从其它函数返回,这种函数叫做头等
函数。在 JavaScript 中,所有函数都是头等
函数。
+将函数为参数或返回值的函数叫做高阶
函数。
+当函数传递给另一个函数或从另一个函数返回时,那些传入或返回的函数可以叫做lambda
。
+tea4GreenTeamFCC
和tea4BlackTeamFCC
变量中。请注意, getTea
函数已被修改,因此它现在将函数作为第一个参数。注意:数据(茶杯数量)作为最后一个参数提供。我们将在后面的课程中对此进行更多讨论。 tea4GreenTeamFCC
和tea4BlackTeamFCC
变量。请注意,getTea
函数已经变了,现在它接收一个函数作为第一个参数。
+注意:数据(茶的数量)作为最后一个参数。我们将在后面的课程中对此进行更多讨论。
+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);
```
+
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']
但输出会略有不同。完成代码并查看是否可以找出问题,然后进入下一个挑战以了解更多信息。 for
循环,它给出了迭代数组索引的精确方向。
+相反,函数式编程是声明式编程的一种形式,通过调用方法或函数来告诉计算机要做什么。
+JavaScript 提供了许多处理常见任务的方法,所以你无需写出计算机应如何执行它们。例如,你可以用 map
函数替代上面提到的 for
循环来处理数组迭代。这有助于避免语义错误,如调试章节介绍的"Off By One Errors"。
+考虑这样的场景:你正在浏览器中浏览网页,并想操作你打开的标签。下面我们来试试用面向对象的思路来描述这种情景。
+窗口对象由选项卡组成,通常会打开多个窗口。窗口对象中每个打开网站的标题都保存在一个数组中。在对浏览器进行了如打开新标签、合并窗口、关闭标签之类的操作后,你需要输出所有打开的标签。关掉的标签将从数组中删除,新打开的标签(为简单起见)则添加到数组的末尾。
+代码编辑器中显示了此功能的实现,其中包含 tabOpen()
,tabClose()
,和 join()
函数。tabs数组是窗口对象的一部分用于储存打开页面的名称。
+
+
+['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']
但输出会略有不同。
+
+修改 Window.prototype.tabClose
使其删除正确的标签。
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);
+```
+
+
+
+
+
+map()
、 filter()
和 reduce()
的使用,是时候用它们来完成一些复杂的挑战了。
+squareList
。任意组合 map()
、filter()
和 reduce()
来完成函数,满足以下条件,当传入实数数组(如,[-3, 4.8, 5, 3, -3.2]
)时,返回仅包含正整数的平方的新数组。
+注意: 函数不应该包含任何形式的 for
或者 while
循环或者 forEach()
函数。
+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: 应该使用 map
、filter
或者 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]);
+```
+
+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
+```
+
+checkPositive
函数中的every
方法检查arr
每个元素是否为正数。该函数应返回一个布尔值。 checkPositive
函数中使用every
方法检查arr
中是否所有元素都是正数,函数应返回一个布尔值。
+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]);
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 } ]
+```
+
+watchList
对象,其中包含有关多部电影的信息。使用filter
和map
的组合返回仅具有title
和rating
键的新对象数组,但imdbRating
大于或等于8.0。请注意,评级值在对象中保存为字符串,您可能希望将它们转换为数字以对它们执行数学运算。 watchList
是包含一些电影信息的对象。结合filter
和map
返回一个只包含title
和rating
属性的新数组,并且imdbRating
值大于或等于 8.0。请注意,评级值在对象中保存为字符串,你可能需要将它转换成数字来执行运算。
+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);
First Class Objects
,这意味着它们可以像任何其他对象一样使用。它们可以保存在变量中,存储在对象中,也可以作为函数参数传递。让我们从一些简单的数组函数开始,这些函数是数组对象原型的方法。在本练习中,我们将查看Array.prototype.map()
,或更简单的map
。请记住, map
方法是一种迭代数组中每个项目的方法。在将回调函数应用于每个元素之后,它会创建一个新数组(不更改原始数组)。 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' ]
+```
+
+watchList
数组保存包含多部电影信息的对象。使用map
从watchList
提取标题和评级,并将新数组保存在rating
变量中。编辑器中的代码当前使用for
循环来执行此操作,将循环功能替换为map
表达式。 watchList
数组保存了包含一些电影信息的对象。使用map
从watchList
中提取标题(title
)和评分(rating
),并将新数组保存在rating
变量里。目前编辑器中的代码是使用for
循环实现,使用map
表达式替换循环功能。
+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
+Array.prototype.reduce()
或简称reduce()
是JavaScript中所有数组操作中最常见的。您可以使用reduce
方法解决几乎任何数组处理问题。 filter
和map
方法不是这种情况,因为它们不允许阵列的两个不同元素之间的交互。例如,如果要比较数组的元素或将它们添加到一起,则filter
或map
无法处理它。 reduce
方法允许更一般的数组处理形式,并且可以显示filter
和map
都可以作为reduce
的特殊应用派生。但是,在我们到达之前,让我们先练习使用reduce
。 reduce()
(即Array.prototype.reduce()
),是 JavaScript 所有数组操作中最常用的方法。几乎可以用reduce
方法解决所有数组处理问题。
+
+reduce
方法是处理数组更通用的方式,而且filter
和map
方法都可以当作是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 }
+```
+
+watchList
对象,其中包含有关多部电影的信息。使用reduce
查找Christopher Nolan指导的电影的平均IMDB评级。回想一下先前的挑战,如何filter
数据并将数据map
到您需要的地方。您可能需要创建其他变量,但将最终平均值保存到变量averageRating
。请注意,评级值在对象中保存为字符串,在用于任何数学运算之前需要转换为数字。 watchList
变量中包含一组存有多部电影信息对象。使用reduce
查找由 Christopher Nolan 导演的电影的 IMDB 评级平均值。回想一下之前的挑战,如何filter
数据,以及使用map
来获取你想要的数据。你可能需要创建一些变量,但是请将最后的平均值保存到averageRating
变量中。请注意,评级在对象中是字符串,需要将其转换为数字再用于数学运算。
+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);
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
+```
+
+checkPositive
函数中的some
方法检查arr
任何元素是否为正数。该函数应返回一个布尔值。 checkPositive
函数值中使用some
检查arr
中是否有元素为正数,函数应返回一个布尔值。
+some
方法。
+ - text: 应该使用some
method.
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]);