chore(i8n,learn): processed translations
This commit is contained in:
committed by
Mrugesh Mohapatra
parent
15047f2d90
commit
e5c44a3ae5
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a77dbc43c33f39daa4429b4f
|
||||
title: 基本类型布尔值的检查
|
||||
title: Boo who
|
||||
challengeType: 5
|
||||
forumTopicId: 16000
|
||||
dashedName: boo-who
|
||||
@ -8,67 +8,67 @@ dashedName: boo-who
|
||||
|
||||
# --description--
|
||||
|
||||
检查一个值是否是[基本类型](https://developer.mozilla.org/zh-CN/docs/Glossary/Primitive)中的布尔值(boolean)类型。函数应返回 true 或者 false。
|
||||
Check if a value is classified as a boolean primitive. Return true or false.
|
||||
|
||||
基本类型中的布尔值为 true 或者 false。
|
||||
Boolean primitives are true and false.
|
||||
|
||||
# --hints--
|
||||
|
||||
`booWho(true)` 应返回 true。
|
||||
`booWho(true)` should return true.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho(true), true);
|
||||
```
|
||||
|
||||
`booWho(false)` 应返回 true。
|
||||
`booWho(false)` should return true.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho(false), true);
|
||||
```
|
||||
|
||||
`booWho([1, 2, 3])` 应返回 false。
|
||||
`booWho([1, 2, 3])` should return false.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho([1, 2, 3]), false);
|
||||
```
|
||||
|
||||
`booWho([].slice)` 应返回 false。
|
||||
`booWho([].slice)` should return false.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho([].slice), false);
|
||||
```
|
||||
|
||||
`booWho({ "a": 1 })` 应返回 false。
|
||||
`booWho({ "a": 1 })` should return false.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho({ a: 1 }), false);
|
||||
```
|
||||
|
||||
`booWho(1)` 应返回 false。
|
||||
`booWho(1)` should return false.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho(1), false);
|
||||
```
|
||||
|
||||
`booWho(NaN)` 应返回 false。
|
||||
`booWho(NaN)` should return false.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho(NaN), false);
|
||||
```
|
||||
|
||||
`booWho("a")` 应返回 false。
|
||||
`booWho("a")` should return false.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho('a'), false);
|
||||
```
|
||||
|
||||
`booWho("true")` 应返回 false。
|
||||
`booWho("true")` should return false.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho('true'), false);
|
||||
```
|
||||
|
||||
`booWho("false")` 应返回 false。
|
||||
`booWho("false")` should return false.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho('false'), false);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a9bd25c716030ec90084d8a1
|
||||
title: 分割数组
|
||||
title: Chunky Monkey
|
||||
challengeType: 5
|
||||
forumTopicId: 16005
|
||||
dashedName: chunky-monkey
|
||||
@ -8,11 +8,11 @@ dashedName: chunky-monkey
|
||||
|
||||
# --description--
|
||||
|
||||
请编写一个函数,该函数将一个数组(第一个参数)拆分成若干长度为 `size`(第二个参数)的子数组,并将它们作为二维数组返回。
|
||||
Write a function that splits an array (first argument) into groups the length of `size` (second argument) and returns them as a two-dimensional array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`chunkArrayInGroups(["a", "b", "c", "d"], 2)` 应返回 `[["a", "b"], ["c", "d"]]`。
|
||||
`chunkArrayInGroups(["a", "b", "c", "d"], 2)` should return `[["a", "b"], ["c", "d"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups(['a', 'b', 'c', 'd'], 2), [
|
||||
@ -21,7 +21,7 @@ assert.deepEqual(chunkArrayInGroups(['a', 'b', 'c', 'd'], 2), [
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)` 应返回 `[[0, 1, 2], [3, 4, 5]]`。
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)` should return `[[0, 1, 2], [3, 4, 5]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3), [
|
||||
@ -30,7 +30,7 @@ assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3), [
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)` 应返回 `[[0, 1], [2, 3], [4, 5]]`。
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)` should return `[[0, 1], [2, 3], [4, 5]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2), [
|
||||
@ -40,7 +40,7 @@ assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2), [
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4)` 应返回 `[[0, 1, 2, 3], [4, 5]]`。
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4)` should return `[[0, 1, 2, 3], [4, 5]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4), [
|
||||
@ -49,7 +49,7 @@ assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4), [
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)` 应返回 `[[0, 1, 2], [3, 4, 5], [6]]`。
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)` should return `[[0, 1, 2], [3, 4, 5], [6]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3), [
|
||||
@ -59,7 +59,7 @@ assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3), [
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)` 应返回 `[[0, 1, 2, 3], [4, 5, 6, 7], [8]]`。
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)` should return `[[0, 1, 2, 3], [4, 5, 6, 7], [8]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4), [
|
||||
@ -69,7 +69,7 @@ assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4), [
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)` 应返回 `[[0, 1], [2, 3], [4, 5], [6, 7], [8]]`。
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)` should return `[[0, 1], [2, 3], [4, 5], [6, 7], [8]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: acda2fb1324d9b0fa741e6b5
|
||||
title: 检查字符串结尾
|
||||
title: Confirm the Ending
|
||||
challengeType: 5
|
||||
forumTopicId: 16006
|
||||
dashedName: confirm-the-ending
|
||||
@ -8,31 +8,31 @@ dashedName: confirm-the-ending
|
||||
|
||||
# --description--
|
||||
|
||||
检查字符串(第一个参数 `str`)是否以给定的目标字符串(第二个参数 `target`)结束。
|
||||
Check if a string (first argument, `str`) ends with the given target string (second argument, `target`).
|
||||
|
||||
这个挑战*可以*用 ES2015 引入的 `.endsWith()` 方法来解决。但在这个挑战中,请使用 JavaScript 的字符串子串方法或正则表达式来通过挑战,而不要使用 `.endsWith()` 方法。
|
||||
This challenge *can* be solved with the `.endsWith()` method, which was introduced in ES2015. But for the purpose of this challenge, we would like you to use one of the JavaScript substring methods instead.
|
||||
|
||||
# --hints--
|
||||
|
||||
`confirmEnding("Bastian", "n")` 应返回 true。
|
||||
`confirmEnding("Bastian", "n")` should return true.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Bastian', 'n') === true);
|
||||
```
|
||||
|
||||
`confirmEnding("Congratulation", "on")` 应返回 true。
|
||||
`confirmEnding("Congratulation", "on")` should return true.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Congratulation', 'on') === true);
|
||||
```
|
||||
|
||||
`confirmEnding("Connor", "n")` 应返回 false。
|
||||
`confirmEnding("Connor", "n")` should return false.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Connor', 'n') === false);
|
||||
```
|
||||
|
||||
`confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification")` 应返回 false。
|
||||
`confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification")` should return false.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -43,31 +43,31 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`confirmEnding("He has to give me a new name", "name")` 应返回 true。
|
||||
`confirmEnding("He has to give me a new name", "name")` should return true.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('He has to give me a new name', 'name') === true);
|
||||
```
|
||||
|
||||
`confirmEnding("Open sesame", "same")` 应返回 true。
|
||||
`confirmEnding("Open sesame", "same")` should return true.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Open sesame', 'same') === true);
|
||||
```
|
||||
|
||||
`confirmEnding("Open sesame", "sage")` 应返回 false。
|
||||
`confirmEnding("Open sesame", "sage")` should return false.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Open sesame', 'sage') === false);
|
||||
```
|
||||
|
||||
`confirmEnding("Open sesame", "game")` 应返回 false。
|
||||
`confirmEnding("Open sesame", "game")` should return false.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Open sesame', 'game') === false);
|
||||
```
|
||||
|
||||
`confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain")` 应返回 false。
|
||||
`confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain")` should return false.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -78,13 +78,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`confirmEnding("Abstraction", "action")` 应该返回 true。
|
||||
`confirmEnding("Abstraction", "action")` should return true.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Abstraction', 'action') === true);
|
||||
```
|
||||
|
||||
不应使用内置方法 `.endsWith()` 来完成挑战。
|
||||
Your code should not use the built-in method `.endsWith()` to solve the challenge.
|
||||
|
||||
```js
|
||||
assert(!/\.endsWith\(.*?\)\s*?;?/.test(code) && !/\['endsWith'\]/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b3
|
||||
title: 将摄氏度转换为华氏度
|
||||
title: Convert Celsius to Fahrenheit
|
||||
challengeType: 1
|
||||
forumTopicId: 16806
|
||||
dashedName: convert-celsius-to-fahrenheit
|
||||
@ -8,43 +8,43 @@ dashedName: convert-celsius-to-fahrenheit
|
||||
|
||||
# --description--
|
||||
|
||||
将摄氏度转换为华氏度的计算方式为:摄氏度乘以 `9/5` 然后加上 `32`。
|
||||
The algorithm to convert from Celsius to Fahrenheit is the temperature in Celsius times `9/5`, plus `32`.
|
||||
|
||||
输入参数 `celsius` 代表一个摄氏度的温度。请根据上述转换公式,将已定义好的 `fahrenheit` 变量赋值为相应的华氏度的温度值。
|
||||
You are given a variable `celsius` representing a temperature in Celsius. Use the variable `fahrenheit` already defined and assign it the Fahrenheit temperature equivalent to the given Celsius temperature. Use the algorithm mentioned above to help convert the Celsius temperature to Fahrenheit.
|
||||
|
||||
# --hints--
|
||||
|
||||
`convertToF(0)` 应返回一个数字。
|
||||
`convertToF(0)` should return a number
|
||||
|
||||
```js
|
||||
assert(typeof convertToF(0) === 'number');
|
||||
```
|
||||
|
||||
`convertToF(-30)` 应返回 `-22`。
|
||||
`convertToF(-30)` should return a value of `-22`
|
||||
|
||||
```js
|
||||
assert(convertToF(-30) === -22);
|
||||
```
|
||||
|
||||
`convertToF(-10)` 应返回 `14`。
|
||||
`convertToF(-10)` should return a value of `14`
|
||||
|
||||
```js
|
||||
assert(convertToF(-10) === 14);
|
||||
```
|
||||
|
||||
`convertToF(0)` 应返回 `32`。
|
||||
`convertToF(0)` should return a value of `32`
|
||||
|
||||
```js
|
||||
assert(convertToF(0) === 32);
|
||||
```
|
||||
|
||||
`convertToF(20)` 应返回 `68`。
|
||||
`convertToF(20)` should return a value of `68`
|
||||
|
||||
```js
|
||||
assert(convertToF(20) === 68);
|
||||
```
|
||||
|
||||
`convertToF(30)` 应返回 `86`。
|
||||
`convertToF(30)` should return a value of `86`
|
||||
|
||||
```js
|
||||
assert(convertToF(30) === 86);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a302f7aae1aa3152a5b413bc
|
||||
title: 计算整数的阶乘
|
||||
title: Factorialize a Number
|
||||
challengeType: 5
|
||||
forumTopicId: 16013
|
||||
dashedName: factorialize-a-number
|
||||
@ -8,43 +8,43 @@ dashedName: factorialize-a-number
|
||||
|
||||
# --description--
|
||||
|
||||
返回一个给定整数的阶乘计算结果。
|
||||
Return the factorial of the provided integer.
|
||||
|
||||
对于整数 n,n 的阶乘就是所有小于等于 n 的正整数的乘积。
|
||||
If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n.
|
||||
|
||||
`n` 的阶乘通常用符号 `n!` 来表示。
|
||||
Factorials are often represented with the shorthand notation `n!`
|
||||
|
||||
例如:`5! = 1 * 2 * 3 * 4 * 5 = 120`
|
||||
For example: `5! = 1 * 2 * 3 * 4 * 5 = 120`
|
||||
|
||||
在这个挑战中,只有非负整数会作为参数传入函数。
|
||||
Only integers greater than or equal to zero will be supplied to the function.
|
||||
|
||||
# --hints--
|
||||
|
||||
`factorialize(5)` 应返回一个数字。
|
||||
`factorialize(5)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof factorialize(5) === 'number');
|
||||
```
|
||||
|
||||
`factorialize(5)` 应返回 120。
|
||||
`factorialize(5)` should return 120.
|
||||
|
||||
```js
|
||||
assert(factorialize(5) === 120);
|
||||
```
|
||||
|
||||
`factorialize(10)` 应返回 3628800。
|
||||
`factorialize(10)` should return 3628800.
|
||||
|
||||
```js
|
||||
assert(factorialize(10) === 3628800);
|
||||
```
|
||||
|
||||
`factorialize(20)` 应返回 2432902008176640000。
|
||||
`factorialize(20)` should return 2432902008176640000.
|
||||
|
||||
```js
|
||||
assert(factorialize(20) === 2432902008176640000);
|
||||
```
|
||||
|
||||
`factorialize(0)` 应返回 1。
|
||||
`factorialize(0)` should return 1.
|
||||
|
||||
```js
|
||||
assert(factorialize(0) === 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: adf08ec01beb4f99fc7a68f2
|
||||
title: 过滤数组中的假值
|
||||
title: Falsy Bouncer
|
||||
challengeType: 5
|
||||
forumTopicId: 16014
|
||||
dashedName: falsy-bouncer
|
||||
@ -8,33 +8,33 @@ dashedName: falsy-bouncer
|
||||
|
||||
# --description--
|
||||
|
||||
从数组中移除所有假值(falsy values)。
|
||||
Remove all falsy values from an array.
|
||||
|
||||
JavaScript 中的假值有 `false`、`null`、`0`、`""`、`undefined`、`NaN`。
|
||||
Falsy values in JavaScript are `false`, `null`, `0`, `""`, `undefined`, and `NaN`.
|
||||
|
||||
提示:可以考虑将每个值都转换为布尔值(boolean)。
|
||||
Hint: Try converting each value to a Boolean.
|
||||
|
||||
# --hints--
|
||||
|
||||
`bouncer([7, "ate", "", false, 9])` 应返回 `[7, "ate", 9]`。
|
||||
`bouncer([7, "ate", "", false, 9])` should return `[7, "ate", 9]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bouncer([7, 'ate', '', false, 9]), [7, 'ate', 9]);
|
||||
```
|
||||
|
||||
`bouncer(["a", "b", "c"])` 应返回 `["a", "b", "c"]`。
|
||||
`bouncer(["a", "b", "c"])` should return `["a", "b", "c"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bouncer(['a', 'b', 'c']), ['a', 'b', 'c']);
|
||||
```
|
||||
|
||||
`bouncer([false, null, 0, NaN, undefined, ""])` 应返回 `[]`。
|
||||
`bouncer([false, null, 0, NaN, undefined, ""])` should return `[]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bouncer([false, null, 0, NaN, undefined, '']), []);
|
||||
```
|
||||
|
||||
`bouncer([1, null, NaN, 2, undefined])`应返回 `[1, 2]`。
|
||||
`bouncer([null, NaN, 1, 2, undefined])` should return `[1, 2]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bouncer([null, NaN, 1, 2, undefined]), [1, 2]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a26cbbe9ad8655a977e1ceb5
|
||||
title: 找出字符串中的最长单词
|
||||
title: Find the Longest Word in a String
|
||||
challengeType: 5
|
||||
forumTopicId: 16015
|
||||
dashedName: find-the-longest-word-in-a-string
|
||||
@ -8,13 +8,13 @@ dashedName: find-the-longest-word-in-a-string
|
||||
|
||||
# --description--
|
||||
|
||||
返回给出的句子中,最长单词的长度。
|
||||
Return the length of the longest word in the provided sentence.
|
||||
|
||||
函数的返回值应是一个数字。
|
||||
Your response should be a number.
|
||||
|
||||
# --hints--
|
||||
|
||||
`findLongestWordLength("The quick brown fox jumped over the lazy dog")` 应返回一个数字。
|
||||
`findLongestWordLength("The quick brown fox jumped over the lazy dog")` should return a number.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -24,7 +24,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestWordLength("The quick brown fox jumped over the lazy dog")` 应返回 6。
|
||||
`findLongestWordLength("The quick brown fox jumped over the lazy dog")` should return 6.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -32,19 +32,19 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestWordLength("May the force be with you")` 应返回 5。
|
||||
`findLongestWordLength("May the force be with you")` should return 5.
|
||||
|
||||
```js
|
||||
assert(findLongestWordLength('May the force be with you') === 5);
|
||||
```
|
||||
|
||||
`findLongestWordLength("Google do a barrel roll")` 应返回 6。
|
||||
`findLongestWordLength("Google do a barrel roll")` should return 6.
|
||||
|
||||
```js
|
||||
assert(findLongestWordLength('Google do a barrel roll') === 6);
|
||||
```
|
||||
|
||||
`findLongestWordLength("What is the average airspeed velocity of an unladen swallow")` 应返回 8。
|
||||
`findLongestWordLength("What is the average airspeed velocity of an unladen swallow")` should return 8.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -54,7 +54,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")` 应返回 19。
|
||||
`findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")` should return 19.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a6e40f1041b06c996f7b2406
|
||||
title: 按参数过滤数组
|
||||
title: Finders Keepers
|
||||
challengeType: 5
|
||||
forumTopicId: 16016
|
||||
dashedName: finders-keepers
|
||||
@ -8,11 +8,11 @@ dashedName: finders-keepers
|
||||
|
||||
# --description--
|
||||
|
||||
请写一个函数来检查数组(第一个参数 `arr`)中的元素,并返回数组中第一个通过校验测试的元素。其中,“通过校验测试”指的是对于数组中的一个元素 `x`,若 `func(x)` 返回的结果为 `true`,则校验测试通过。如果没有元素通过测试,请返回 `undefined`。
|
||||
Create a function that looks through an array `arr` and returns the first element in it that passes a 'truth test'. This means that given an element `x`, the 'truth test' is passed if `func(x)` is `true`. If no element passes the test, return `undefined`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })` 应返回 8。
|
||||
`findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })` should return 8.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -23,7 +23,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })` 应返回 undefined。
|
||||
`findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })` should return undefined.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: af2170cad53daa0770fabdea
|
||||
title: 比较字符串
|
||||
title: Mutations
|
||||
challengeType: 5
|
||||
forumTopicId: 16025
|
||||
dashedName: mutations
|
||||
@ -8,89 +8,83 @@ dashedName: mutations
|
||||
|
||||
# --description--
|
||||
|
||||
输入参数是一个数组,其中包含两个字符串元素。如果数组里的第一个字符串包含了第二个字符串中的所有字母,则返回 true。
|
||||
Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.
|
||||
|
||||
例如,`["hello", "Hello"]` 应该返回 true。因为在忽略大小写的情况下,第一个字符串中包含了第二个字符串里出现的所有字母。
|
||||
For example, `["hello", "Hello"]`, should return true because all of the letters in the second string are present in the first, ignoring case.
|
||||
|
||||
而 `["hello", "hey"]` 应该返回 false。因为第一个字符串 "hello" 没有包含字母 "y"。
|
||||
The arguments `["hello", "hey"]` should return false because the string "hello" does not contain a "y".
|
||||
|
||||
最后,`["Alien", "line"]` 应该返回 true。因为 "line" 中的所有字母都出现在了 "Alien" 中。
|
||||
Lastly, `["Alien", "line"]`, should return true because all of the letters in "line" are present in "Alien".
|
||||
|
||||
# --hints--
|
||||
|
||||
`mutation(["hello", "hey"])` 应返回 false。
|
||||
`mutation(["hello", "hey"])` should return false.
|
||||
|
||||
```js
|
||||
assert(mutation(['hello', 'hey']) === false);
|
||||
```
|
||||
|
||||
`mutation(["hello", "Hello"])` 应返回 true。
|
||||
`mutation(["hello", "Hello"])` should return true.
|
||||
|
||||
```js
|
||||
assert(mutation(['hello', 'Hello']) === true);
|
||||
```
|
||||
|
||||
`mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"])` 应返回 true。
|
||||
`mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"])` should return true.
|
||||
|
||||
```js
|
||||
assert(mutation(['zyxwvutsrqponmlkjihgfedcba', 'qrstu']) === true);
|
||||
```
|
||||
|
||||
`mutation(["Mary", "Army"])` 应返回 true。
|
||||
`mutation(["Mary", "Army"])` should return true.
|
||||
|
||||
```js
|
||||
assert(mutation(['Mary', 'Army']) === true);
|
||||
```
|
||||
|
||||
`mutation(["Mary", "Aarmy"])` 应返回 true。
|
||||
`mutation(["Mary", "Aarmy"])` should return true.
|
||||
|
||||
```js
|
||||
assert(mutation(['Mary', 'Aarmy']) === true);
|
||||
```
|
||||
|
||||
`mutation(["Alien", "line"])` 应返回 true。
|
||||
`mutation(["Alien", "line"])` should return true.
|
||||
|
||||
```js
|
||||
assert(mutation(['Alien', 'line']) === true);
|
||||
```
|
||||
|
||||
`mutation(["floor", "for"])` 应返回 true。
|
||||
`mutation(["floor", "for"])` should return true.
|
||||
|
||||
```js
|
||||
assert(mutation(['floor', 'for']) === true);
|
||||
```
|
||||
|
||||
`mutation(["hello", "neo"])` 应返回 false。
|
||||
`mutation(["hello", "neo"])` should return false.
|
||||
|
||||
```js
|
||||
assert(mutation(['hello', 'neo']) === false);
|
||||
```
|
||||
|
||||
`mutation(["voodoo", "no"])` 应返回 false。
|
||||
`mutation(["voodoo", "no"])` should return false.
|
||||
|
||||
```js
|
||||
assert(mutation(['voodoo', 'no']) === false);
|
||||
```
|
||||
|
||||
`mutation(["voodoo", "no"])` 应返回 false。
|
||||
|
||||
```js
|
||||
assert(mutation(['voodoo', 'no']) === false);
|
||||
```
|
||||
|
||||
`mutation(["ate", "date"]` 应返回 false。
|
||||
`mutation(["ate", "date"]` should return false.
|
||||
|
||||
```js
|
||||
assert(mutation(['ate', 'date']) === false);
|
||||
```
|
||||
|
||||
`mutation(["Tiger", "Zebra"])` 应返回 false。
|
||||
`mutation(["Tiger", "Zebra"])` should return false.
|
||||
|
||||
```js
|
||||
assert(mutation(['Tiger', 'Zebra']) === false);
|
||||
```
|
||||
|
||||
`mutation(["Noel", "Ole"])` 应返回 true。
|
||||
`mutation(["Noel", "Ole"])` should return true.
|
||||
|
||||
```js
|
||||
assert(mutation(['Noel', 'Ole']) === true);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: afcc8d540bea9ea2669306b6
|
||||
title: 重复输出字符串
|
||||
title: Repeat a String Repeat a String
|
||||
challengeType: 5
|
||||
forumTopicId: 16041
|
||||
dashedName: repeat-a-string-repeat-a-string
|
||||
@ -8,55 +8,53 @@ dashedName: repeat-a-string-repeat-a-string
|
||||
|
||||
# --description--
|
||||
|
||||
为`num` times(第二个参数)重复给定的字符串`str` (第一个参数)。如果`num`不是正数,则返回空字符串。如果卡住,请记得使用[Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck-coding/19514) 。编写自己的代码。
|
||||
|
||||
将一个给定的字符串 `str`(第一个参数)重复输出 `num`(第二个参数)次。如果 `num` 不是正数,返回空字符串。在这个挑战中,请不要使用 JavaScript 内置的 `.repeat()` 方法。
|
||||
Repeat a given string `str` (first argument) for `num` times (second argument). Return an empty string if `num` is not a positive number. For the purpose of this challenge, do *not* use the built-in `.repeat()` method.
|
||||
|
||||
# --hints--
|
||||
|
||||
`repeatStringNumTimes("*", 3)` 应返回 `"***"`。
|
||||
`repeatStringNumTimes("*", 3)` should return `"***"`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('*', 3) === '***');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", 3)` 应返回 `"abcabcabc"`。
|
||||
`repeatStringNumTimes("abc", 3)` should return `"abcabcabc"`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', 3) === 'abcabcabc');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", 4)` 应返回 `"abcabcabcabc"`。
|
||||
`repeatStringNumTimes("abc", 4)` should return `"abcabcabcabc"`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', 4) === 'abcabcabcabc');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", 1)` 应返回 `"abc"`。
|
||||
`repeatStringNumTimes("abc", 1)` should return `"abc"`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', 1) === 'abc');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("*", 8)` 应返回 `"********"`。
|
||||
`repeatStringNumTimes("*", 8)` should return `"********"`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('*', 8) === '********');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", -2)` 应返回 `""`。
|
||||
`repeatStringNumTimes("abc", -2)` should return `""`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', -2) === '');
|
||||
```
|
||||
|
||||
不应使用内置的 `repeat()` 方法。
|
||||
The built-in `repeat()` method should not be used.
|
||||
|
||||
```js
|
||||
assert(!/\.repeat/g.test(code));
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", 0)` 应返回 `""`。
|
||||
`repeatStringNumTimes("abc", 0)` should return `""`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', 0) === '');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a789b3483989747d63b0e427
|
||||
title: 找出多个数组中的最大数字
|
||||
title: Return Largest Numbers in Arrays
|
||||
challengeType: 5
|
||||
forumTopicId: 16042
|
||||
dashedName: return-largest-numbers-in-arrays
|
||||
@ -8,13 +8,13 @@ dashedName: return-largest-numbers-in-arrays
|
||||
|
||||
# --description--
|
||||
|
||||
请返回一个数组,该数组由参数中每个子数组中的最大数字组成。为简单起见,给出的数组总会包含 4 个子数组。
|
||||
Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.
|
||||
|
||||
别忘了,你可以通过 for 循环遍历一个数组,并用 `arr[i]` 的写法来访问数组中的元素。
|
||||
Remember, you can iterate through an array with a simple for loop, and access each member with array syntax `arr[i]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])` 应返回一个数组。
|
||||
`largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])` should return an array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -27,7 +27,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])` 应返回 `[27, 5, 39, 1001]`。
|
||||
`largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])` should return `[27, 5, 39, 1001]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -41,7 +41,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]])` 应返回 `[9, 35, 97, 1000000]`。
|
||||
`largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]])` should return `[9, 35, 97, 1000000]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -55,7 +55,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])` 应返回 `[25, 48, 21, -3]`。
|
||||
`largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])` should return `[25, 48, 21, -3]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a202eed8fc186c8434cb6d61
|
||||
title: 反转字符串
|
||||
title: Reverse a String
|
||||
challengeType: 5
|
||||
forumTopicId: 16043
|
||||
dashedName: reverse-a-string
|
||||
@ -8,33 +8,33 @@ dashedName: reverse-a-string
|
||||
|
||||
# --description--
|
||||
|
||||
请反转传入函数的字符串。
|
||||
Reverse the provided string.
|
||||
|
||||
在反转字符串之前,你可能需要将其切分成包含字符的数组。
|
||||
You may need to turn the string into an array before you can reverse it.
|
||||
|
||||
函数的返回结果应为字符串。
|
||||
Your result must be a string.
|
||||
|
||||
# --hints--
|
||||
|
||||
`reverseString("hello")` 应返回一个字符串。
|
||||
`reverseString("hello")` should return a string.
|
||||
|
||||
```js
|
||||
assert(typeof reverseString('hello') === 'string');
|
||||
```
|
||||
|
||||
`reverseString("hello")` 应返回 `"olleh"`。
|
||||
`reverseString("hello")` should become `"olleh"`.
|
||||
|
||||
```js
|
||||
assert(reverseString('hello') === 'olleh');
|
||||
```
|
||||
|
||||
`reverseString("Howdy")` 应返回 `"ydwoH"`。
|
||||
`reverseString("Howdy")` should become `"ydwoH"`.
|
||||
|
||||
```js
|
||||
assert(reverseString('Howdy') === 'ydwoH');
|
||||
```
|
||||
|
||||
`reverseString("Greetings from Earth")` 应返回 `"htraE morf sgniteerG"`。
|
||||
`reverseString("Greetings from Earth")` should return `"htraE morf sgniteerG"`.
|
||||
|
||||
```js
|
||||
assert(reverseString('Greetings from Earth') === 'htraE morf sgniteerG');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 579e2a2c335b9d72dd32e05c
|
||||
title: Slice 与 Splice
|
||||
title: Slice and Splice
|
||||
challengeType: 5
|
||||
forumTopicId: 301148
|
||||
dashedName: slice-and-splice
|
||||
@ -8,29 +8,29 @@ dashedName: slice-and-splice
|
||||
|
||||
# --description--
|
||||
|
||||
本挑战的输入参数为两个数组和一个索引值。
|
||||
You are given two arrays and an index.
|
||||
|
||||
请使用数组的 `slice` 和 `splice` 方法,将第一个数组中的所有元素依次复制到第二个数组中。
|
||||
Copy each element of the first array into the second array, in order.
|
||||
|
||||
请注意,你需要从第二个数组索引值为 `n`(函数的第三个参数)的地方开始插入。
|
||||
Begin inserting elements at index `n` of the second array.
|
||||
|
||||
最后,请返回插入元素后的数组。作为输入参数的两个数组在函数执行前后应保持不变。
|
||||
Return the resulting array. The input arrays should remain the same after the function runs.
|
||||
|
||||
# --hints--
|
||||
|
||||
`frankenSplice([1, 2, 3], [4, 5], 1)` 应返回 `[4, 1, 2, 3, 5]`。
|
||||
`frankenSplice([1, 2, 3], [4, 5], 1)` should return `[4, 1, 2, 3, 5]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(frankenSplice([1, 2, 3], [4, 5], 1), [4, 1, 2, 3, 5]);
|
||||
```
|
||||
|
||||
`frankenSplice([1, 2], ["a", "b"], 1)` 应返回 `["a", 1, 2, "b"]`。
|
||||
`frankenSplice([1, 2], ["a", "b"], 1)` should return `["a", 1, 2, "b"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(frankenSplice(testArr1, testArr2, 1), ['a', 1, 2, 'b']);
|
||||
```
|
||||
|
||||
`frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)` 应返回 `["head", "shoulders", "claw", "tentacle", "knees", "toes"]`。
|
||||
`frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)` should return `["head", "shoulders", "claw", "tentacle", "knees", "toes"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -43,20 +43,20 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
第一个数组中的所有元素都应按原始顺序添加到第二个数组中。
|
||||
All elements from the first array should be added to the second array in their original order.
|
||||
|
||||
```js
|
||||
assert.deepEqual(frankenSplice([1, 2, 3, 4], [], 0), [1, 2, 3, 4]);
|
||||
```
|
||||
|
||||
函数运行后,第一个数组应保持不变。
|
||||
The first array should remain the same after the function runs.
|
||||
|
||||
```js
|
||||
frankenSplice(testArr1, testArr2, 1);
|
||||
assert.deepEqual(testArr1, [1, 2]);
|
||||
```
|
||||
|
||||
函数运行后,第二个数组应保持不变。
|
||||
The second array should remain the same after the function runs.
|
||||
|
||||
```js
|
||||
frankenSplice(testArr1, testArr2, 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: ab6137d4e35944e21037b769
|
||||
title: 句中单词首字母大写
|
||||
title: Title Case a Sentence
|
||||
challengeType: 5
|
||||
forumTopicId: 16088
|
||||
dashedName: title-case-a-sentence
|
||||
@ -8,31 +8,31 @@ dashedName: title-case-a-sentence
|
||||
|
||||
# --description--
|
||||
|
||||
请将传入的字符串中,每个单词的第一个字母变成大写并返回。注意除首字母外,其余的字符都应是小写的。
|
||||
Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case.
|
||||
|
||||
另外请注意,像是 “the”、“of” 之类的连接词的首字母也要大写。
|
||||
For the purpose of this exercise, you should also capitalize connecting words like "the" and "of".
|
||||
|
||||
# --hints--
|
||||
|
||||
`titleCase("I'm a little tea pot")` 应返回一个字符串。
|
||||
`titleCase("I'm a little tea pot")` should return a string.
|
||||
|
||||
```js
|
||||
assert(typeof titleCase("I'm a little tea pot") === 'string');
|
||||
```
|
||||
|
||||
`titleCase("I'm a little tea pot")` 应返回 `I'm A Little Tea Pot`。
|
||||
`titleCase("I'm a little tea pot")` should return `I'm A Little Tea Pot`.
|
||||
|
||||
```js
|
||||
assert(titleCase("I'm a little tea pot") === "I'm A Little Tea Pot");
|
||||
```
|
||||
|
||||
`titleCase("sHoRt AnD sToUt")` 应返回 `Short And Stout`。
|
||||
`titleCase("sHoRt AnD sToUt")` should return `Short And Stout`.
|
||||
|
||||
```js
|
||||
assert(titleCase('sHoRt AnD sToUt') === 'Short And Stout');
|
||||
```
|
||||
|
||||
`titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")` 应返回 `Here Is My Handle Here Is My Spout`。
|
||||
`titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")` should return `Here Is My Handle Here Is My Spout`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: ac6993d51946422351508a41
|
||||
title: 截断字符串
|
||||
title: Truncate a String
|
||||
challengeType: 5
|
||||
forumTopicId: 16089
|
||||
dashedName: truncate-a-string
|
||||
@ -8,11 +8,11 @@ dashedName: truncate-a-string
|
||||
|
||||
# --description--
|
||||
|
||||
如果传入的字符串(第一个参数)的长度大于传入的值(第二个参数),请在这个位置截断它并在后面加上 `...`,然后返回结果。
|
||||
Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a `...` ending.
|
||||
|
||||
# --hints--
|
||||
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", 8)` 应返回 "A-tisket..."。
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", 8)` should return "A-tisket...".
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -21,7 +21,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`truncateString("Peter Piper picked a peck of pickled peppers", 11)` 应返回 "Peter Piper..."。
|
||||
`truncateString("Peter Piper picked a peck of pickled peppers", 11)` should return "Peter Piper...".
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -30,7 +30,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)` 应返回 "A-tisket a-tasket A green and yellow basket"。
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)` should return "A-tisket a-tasket A green and yellow basket".
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -41,7 +41,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)` 应返回 "A-tisket a-tasket A green and yellow basket"。
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)` should return "A-tisket a-tasket A green and yellow basket".
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -52,13 +52,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`truncateString("A-", 1)` 应返回 "A..."。
|
||||
`truncateString("A-", 1)` should return "A...".
|
||||
|
||||
```js
|
||||
assert(truncateString('A-', 1) === 'A...');
|
||||
```
|
||||
|
||||
`truncateString("Absolutely Longer", 2)` 应返回 "Ab..."。
|
||||
`truncateString("Absolutely Longer", 2)` should return "Ab...".
|
||||
|
||||
```js
|
||||
assert(truncateString('Absolutely Longer', 2) === 'Ab...');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a24c1a4622e3c05097f71d67
|
||||
title: 找出元素在排序后数组中的索引
|
||||
title: Where do I Belong
|
||||
challengeType: 5
|
||||
forumTopicId: 16094
|
||||
dashedName: where-do-i-belong
|
||||
@ -8,105 +8,105 @@ dashedName: where-do-i-belong
|
||||
|
||||
# --description--
|
||||
|
||||
第一个参数的数组在排序后,将一个值(第二个参数)插入该数组,并使数组保持有序。返回这个新插入元素的**最小**索引值(应为一个数字)。
|
||||
Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number.
|
||||
|
||||
例如,`getIndexToIns([1,2,3,4], 1.5)` 应该返回 `1` 因为 `1.5` 大于 `1`(索引为 0)且小于 `2`(索引为 1)。
|
||||
For example, `getIndexToIns([1,2,3,4], 1.5)` should return `1` because it is greater than `1` (index 0), but less than `2` (index 1).
|
||||
|
||||
同样地,`getIndexToIns([20,3,5], 19)` 应该返回 `2`。因为数组排序后会变成 `[3,5,20]`,而 `19` 小于 `20`(索引为 2)且大于 `5`(索引为 1)。
|
||||
Likewise, `getIndexToIns([20,3,5], 19)` should return `2` because once the array has been sorted it will look like `[3,5,20]` and `19` is less than `20` (index 2) and greater than `5` (index 1).
|
||||
|
||||
# --hints--
|
||||
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 35)` 应返回 `3`。
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 35)` should return `3`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([10, 20, 30, 40, 50], 35) === 3);
|
||||
```
|
||||
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 35)` 应返回一个数字。
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 35)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([10, 20, 30, 40, 50], 35) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 30)` 应返回 `2`。
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 30)` should return `2`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([10, 20, 30, 40, 50], 30) === 2);
|
||||
```
|
||||
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 30)` 应返回一个数字。
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 30)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([10, 20, 30, 40, 50], 30) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([40, 60], 50)` 应返回 `1`。
|
||||
`getIndexToIns([40, 60], 50)` should return `1`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([40, 60], 50) === 1);
|
||||
```
|
||||
|
||||
`getIndexToIns([40, 60], 50)` 应返回一个数字。
|
||||
`getIndexToIns([40, 60], 50)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([40, 60], 50) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([3, 10, 5], 3)` 应返回 `0`。
|
||||
`getIndexToIns([3, 10, 5], 3)` should return `0`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([3, 10, 5], 3) === 0);
|
||||
```
|
||||
|
||||
`getIndexToIns([3, 10, 5], 3)` 应返回一个数字。
|
||||
`getIndexToIns([3, 10, 5], 3)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([3, 10, 5], 3) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([5, 3, 20, 3], 5)` 应返回 `2`。
|
||||
`getIndexToIns([5, 3, 20, 3], 5)` should return `2`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([5, 3, 20, 3], 5) === 2);
|
||||
```
|
||||
|
||||
`getIndexToIns([5, 3, 20, 3], 5)` 应返回一个数字。
|
||||
`getIndexToIns([5, 3, 20, 3], 5)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([5, 3, 20, 3], 5) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([2, 20, 10], 19)` 应返回 `2`。
|
||||
`getIndexToIns([2, 20, 10], 19)` should return `2`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([2, 20, 10], 19) === 2);
|
||||
```
|
||||
|
||||
`getIndexToIns([2, 20, 10], 19)` 应返回一个数字。
|
||||
`getIndexToIns([2, 20, 10], 19)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([2, 20, 10], 19) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([2, 5, 10], 15)` 应返回 `3`。
|
||||
`getIndexToIns([2, 5, 10], 15)` should return `3`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([2, 5, 10], 15) === 3);
|
||||
```
|
||||
|
||||
`getIndexToIns([2, 5, 10], 15)` 应返回一个数字。
|
||||
`getIndexToIns([2, 5, 10], 15)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([2, 5, 10], 15) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([], 1)`应该返回 `0`。
|
||||
`getIndexToIns([], 1)` should return `0`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([], 1) === 0);
|
||||
```
|
||||
|
||||
`getIndexToIns([], 1)` 应返回一个数字。
|
||||
`getIndexToIns([], 1)` should return a number.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([], 1) === 'number');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a661e0f1068aca922b3ef17
|
||||
title: 使用方括号访问数组的元素
|
||||
title: Access an Array's Contents Using Bracket Notation
|
||||
challengeType: 1
|
||||
forumTopicId: 301149
|
||||
dashedName: access-an-arrays-contents-using-bracket-notation
|
||||
@ -8,55 +8,55 @@ dashedName: access-an-arrays-contents-using-bracket-notation
|
||||
|
||||
# --description--
|
||||
|
||||
所有数据结构的基本特性是,它们不仅可以存储数据,还可以让我们按需访问存放在其中的数据。我们已经学习了如何创建数组,现在让我们来学习如何访问数组中的数据。
|
||||
The fundamental feature of any data structure is, of course, the ability to not only store data, but to be able to retrieve that data on command. So, now that we've learned how to create an array, let's begin to think about how we can access that array's information.
|
||||
|
||||
我们先定义一个包含 3 个元素的数组:
|
||||
When we define a simple array as seen below, there are 3 items in it:
|
||||
|
||||
```js
|
||||
let ourArray = ["a", "b", "c"];
|
||||
```
|
||||
|
||||
在数组中,内部的每个元素都有一个与之对应的<dfn>索引</dfn>(<dfn>index</dfn>)。索引既是该元素在数组中的位置,也是我们访问该元素的参考。需要注意的是,JavaScript 数组的索引是从 0 开始的(这种从 0 开始的规则叫做 <dfn>zero-indexed</dfn>),即数组的第一个元素是在数组中的***第 0 个***位置,而不是第 1 个位置。要从数组中获取一个元素,我们可以在数组字面量后面加一个用方括号(`[]`)括起来的索引。不过习惯上,我们会通过表示数组的变量名来访问,而不是直接通过字面量。这种从数组中读取元素的方式叫做<dfn>方括号表示法</dfn>(<dfn>bracket notation</dfn>)。如果我们要从数组 `ourArray` 中获取数据元素 `"a"` 并将其赋值给另一个变量,可以这样写:
|
||||
In an array, each array item has an <dfn>index</dfn>. This index doubles as the position of that item in the array, and how you reference it. However, it is important to note, that JavaScript arrays are <dfn>zero-indexed</dfn>, meaning that the first element of an array is actually at the ***zeroth*** position, not the first. In order to retrieve an element from an array we can enclose an index in brackets and append it to the end of an array, or more commonly, to a variable which references an array object. This is known as <dfn>bracket notation</dfn>. For example, if we want to retrieve the `"a"` from `ourArray` and assign it to a variable, we can do so with the following code:
|
||||
|
||||
```js
|
||||
let ourVariable = ourArray[0];
|
||||
// ourVariable 的值为 "a"
|
||||
// ourVariable equals "a"
|
||||
```
|
||||
|
||||
除了使用索引来获取某个元素值以外,你还可以通过类似的写法来*设置*一个索引位置的元素值:
|
||||
In addition to accessing the value associated with an index, you can also *set* an index to a value using the same notation:
|
||||
|
||||
```js
|
||||
ourArray[1] = "not b anymore";
|
||||
// ourArray 现在的值为 ["a", "not b anymore", "c"];
|
||||
// ourArray now equals ["a", "not b anymore", "c"];
|
||||
```
|
||||
|
||||
在上面的代码中,我们用方括号表示法把索引为 1 的元素从 `"b"` 改成了 `"not b anymore"`。
|
||||
Using bracket notation, we have now reset the item at index 1 from `"b"`, to `"not b anymore"`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
在本挑战中,请将 `myArray` 中的第二个元素(索引为 `1`)设置为除了 `"b"` 以外的任意值。
|
||||
In order to complete this challenge, set the 2nd position (index `1`) of `myArray` to anything you want, besides `"b"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray[0]` 应为 `"a"`。
|
||||
`myArray[0]` should be equal to `"a"`
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[0], 'a');
|
||||
```
|
||||
|
||||
`myArray[1]` 不应为 `"b"`。
|
||||
`myArray[1]` should not be equal to `"b"`
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(myArray[1], 'b');
|
||||
```
|
||||
|
||||
`myArray[2]` 应为 `"c"`。
|
||||
`myArray[2]` should be equal to `"c"`
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[2], 'c');
|
||||
```
|
||||
|
||||
`myArray[3]` 应为 `"d"`。
|
||||
`myArray[3]` should be equal to `"d"`
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[3], 'd');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b1a
|
||||
title: 使用方括号访问属性名称
|
||||
title: Access Property Names with Bracket Notation
|
||||
challengeType: 1
|
||||
forumTopicId: 301150
|
||||
dashedName: access-property-names-with-bracket-notation
|
||||
@ -8,28 +8,28 @@ dashedName: access-property-names-with-bracket-notation
|
||||
|
||||
# --description--
|
||||
|
||||
在关于对象的第一个挑战中,我们提到可以在一对方括号中用一个变量作为属性名来访问属性的值。假设一个超市收银台程序中有一个 `foods` 对象,并且有一个函数会设置 `selectedFood`;如果我们需要查询 `foods` 对象中,某种食物是否存在,可以这样实现:
|
||||
In the first object challenge we mentioned the use of bracket notation as a way to access property values using the evaluation of a variable. For instance, imagine that our `foods` object is being used in a program for a supermarket cash register. We have some function that sets the `selectedFood` and we want to check our `foods` object for the presence of that food. This might look like:
|
||||
|
||||
```js
|
||||
let selectedFood = getCurrentFood(scannedItem);
|
||||
let inventory = foods[selectedFood];
|
||||
```
|
||||
|
||||
上述代码会先读取 `selectedFood` 变量的值,并返回 `foods` 对象中以该值命名的属性所对应的属性值。若没有以该值命名的属性,则会返回 `undefined`。有时候对象的属性名在运行之前是不确定的,或者我们需要动态地访问对象的属性值。在这些场景下,方括号表示法就变得十分有用。
|
||||
This code will evaluate the value stored in the `selectedFood` variable and return the value of that key in the `foods` object, or `undefined` if it is not present. Bracket notation is very useful because sometimes object properties are not known before runtime or we need to access them in a more dynamic way.
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了 `checkInventory` 函数,它接受一个被扫描到的商品名作为输入参数。请让这个函数返回 `foods` 对象中,以 `scannedItem` 的值所命名的属性对应的属性值。在本挑战中,只有合理有效的属性名会作为参数传入 `checkInventory`,因此你不需要处理参数无效的情况。
|
||||
We've defined a function, `checkInventory`, which receives a scanned item as an argument. Return the current value of the `scannedItem` key in the `foods` object. You can assume that only valid keys will be provided as an argument to `checkInventory`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`checkInventory` 应是一个函数。
|
||||
`checkInventory` should be a function.
|
||||
|
||||
```js
|
||||
assert.strictEqual(typeof checkInventory, 'function');
|
||||
```
|
||||
|
||||
`foods` 对象应只包含以下键值对:`apples: 25`、`oranges: 32`、`plums: 28`、`bananas: 13`、`grapes: 35`、`strawberries: 27`。
|
||||
The `foods` object should have only the following key-value pairs: `apples: 25`, `oranges: 32`, `plums: 28`, `bananas: 13`, `grapes: 35`, `strawberries: 27`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(foods, {
|
||||
@ -42,19 +42,19 @@ assert.deepEqual(foods, {
|
||||
});
|
||||
```
|
||||
|
||||
`checkInventory("apples")` 应返回 `25`。
|
||||
`checkInventory("apples")` should return `25`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(checkInventory('apples'), 25);
|
||||
```
|
||||
|
||||
`checkInventory("bananas")` 应返回 `13`。
|
||||
`checkInventory("bananas")` should return `13`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(checkInventory('bananas'), 13);
|
||||
```
|
||||
|
||||
`checkInventory("strawberries")` 应返回 `27`。
|
||||
`checkInventory("strawberries")` should return `27`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(checkInventory('strawberries'), 27);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b0e
|
||||
title: 使用 push() 和 unshift() 为数组添加元素
|
||||
title: Add Items to an Array with push() and unshift()
|
||||
challengeType: 1
|
||||
forumTopicId: 301151
|
||||
dashedName: add-items-to-an-array-with-push-and-unshift
|
||||
@ -8,30 +8,28 @@ dashedName: add-items-to-an-array-with-push-and-unshift
|
||||
|
||||
# --description--
|
||||
|
||||
数组的长度与数组能包含的数据类型一样,都是不固定的。数组可以包含任意数量的元素,可以不限次数地往数组中添加元素或者从中移除元素。总之,数组是<dfn>可变的</dfn>(<dfn>mutable</dfn>)。在本挑战中,我们要学习两种修改数组的方法:`Array.push()` 和 `Array.unshift()`。
|
||||
An array's length, like the data types it can contain, is not fixed. Arrays can be defined with a length of any number of elements, and elements can be added or removed over time; in other words, arrays are <dfn>mutable</dfn>. In this challenge, we will look at two methods with which we can programmatically modify an array: `Array.push()` and `Array.unshift()`.
|
||||
|
||||
这两个方法都接收一个或多个元素作为参数,并会将参数中的元素添加到该数组中。`push()` 方法会将元素插入到数组的末尾,而 `unshift()` 方法会将元素插入到数组的开头。请看以下例子:
|
||||
Both methods take one or more elements as parameters and add those elements to the array the method is being called on; the `push()` method adds elements to the end of an array, and `unshift()` adds elements to the beginning. Consider the following:
|
||||
|
||||
```js
|
||||
let twentyThree = 'XXIII';
|
||||
let romanNumerals = ['XXI', 'XXII'];
|
||||
|
||||
romanNumerals.unshift('XIX', 'XX');
|
||||
// 数组现在为 ['XIX', 'XX', 'XXI', 'XXII']
|
||||
// now equals ['XIX', 'XX', 'XXI', 'XXII']
|
||||
|
||||
romanNumerals.push(twentyThree);
|
||||
// 数组现在为 ['XIX', 'XX', 'XXI', 'XXII', 'XXIII']
|
||||
// now equals ['XIX', 'XX', 'XXI', 'XXII', 'XXIII']Notice that we can also pass variables, which allows us even greater flexibility in dynamically modifying our array's data.
|
||||
```
|
||||
|
||||
**注意:**我们甚至可以传入变量,这在动态改变数组数据的场景下十分有用。
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个 `mixedNumbers` 函数,它接收一个数组作为参数。请你修改这个函数,使用 `push()` 和 `unshift()` 来将 `'I', 2, 'three'` 插入到数组开头,将 `7, 'VIII', 9` 插入到数组的末尾,使得这个函数返回一个依次包含 1 至 9。
|
||||
We have defined a function, `mixedNumbers`, which we are passing an array as an argument. Modify the function by using `push()` and `unshift()` to add `'I', 2, 'three'` to the beginning of the array and `7, 'VIII', 9` to the end so that the returned array contains representations of the numbers 1-9 in order.
|
||||
|
||||
# --hints--
|
||||
|
||||
`mixedNumbers(["IV", 5, "six"])` 应返回 `["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]`。
|
||||
`mixedNumbers(["IV", 5, "six"])` should now return `["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(mixedNumbers(['IV', 5, 'six']), [
|
||||
@ -47,13 +45,13 @@ assert.deepEqual(mixedNumbers(['IV', 5, 'six']), [
|
||||
]);
|
||||
```
|
||||
|
||||
`mixedNumbers` 函数中应调用 `push()` 方法。
|
||||
The `mixedNumbers` function should utilize the `push()` method
|
||||
|
||||
```js
|
||||
assert(mixedNumbers.toString().match(/\.push/));
|
||||
```
|
||||
|
||||
`mixedNumbers` 函数中应调用 `unshift()` 方法。
|
||||
The `mixedNumbers` function should utilize the `unshift()` method
|
||||
|
||||
```js
|
||||
assert(mixedNumbers.toString().match(/\.unshift/));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d78b3367417b2b2512b11
|
||||
title: 使用 splice() 添加元素
|
||||
title: Add Items Using splice()
|
||||
challengeType: 1
|
||||
forumTopicId: 301152
|
||||
dashedName: add-items-using-splice
|
||||
@ -8,7 +8,7 @@ dashedName: add-items-using-splice
|
||||
|
||||
# --description--
|
||||
|
||||
还记得在上个挑战中我们提到 `splice()` 方法最多可以接收 3 个参数吗?除了移除元素,我们还可以利用它的第三个参数来向数组中*添加*元素。第三个参数可以是一个或多个元素,这些元素会被添加到数组中。这样,我们能够便捷地将数组中的一个或多个连续元素换成其他的元素。例如:
|
||||
Remember in the last challenge we mentioned that `splice()` can take up to three parameters? Well, you can use the third parameter, comprised of one or more element(s), to add to the array. This can be incredibly useful for quickly switching out an element, or a set of elements, for another.
|
||||
|
||||
```js
|
||||
const numbers = [10, 11, 12, 12, 15];
|
||||
@ -16,20 +16,20 @@ const startIndex = 3;
|
||||
const amountToDelete = 1;
|
||||
|
||||
numbers.splice(startIndex, amountToDelete, 13, 14);
|
||||
// 第二个 12 被移除,在第二个 12 的索引处添加 13、14。
|
||||
// the second entry of 12 is removed, and we add 13 and 14 at the same index
|
||||
console.log(numbers);
|
||||
// 返回 [ 10, 11, 12, 13, 14, 15 ]
|
||||
// returns [ 10, 11, 12, 13, 14, 15 ]
|
||||
```
|
||||
|
||||
在上面的代码中,数组一开始包含了若干数字。接着,我们调用 `splice()` 方法,索引为 (3) 的地方开始删除元素,删除的元素数量是 (1)。然后,(13, 14) 是在删除位置插入的元素,可以在 `amountToDelete` 后面传入任意数量的元素(以逗号分隔),每个都会被插入到数组中。
|
||||
Here, we begin with an array of numbers. Then, we pass the following to `splice()`: The index at which to begin deleting elements (3), the number of elements to be deleted (1), and the remaining arguments (13, 14) will be inserted starting at that same index. Note that there can be any number of elements (separated by commas) following `amountToDelete`, each of which gets inserted.
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个 `htmlColorNames` 函数,它以一个 HTML 颜色的数组作为输入参数。请修改这个函数,使用 `splice()` 来移除数组中的前两个元素,并在对应的位置上添加 `'DarkSalmon'` 和 `'BlanchedAlmond'`。
|
||||
We have defined a function, `htmlColorNames`, which takes an array of HTML colors as an argument. Modify the function using `splice()` to remove the first two elements of the array and add `'DarkSalmon'` and `'BlanchedAlmond'` in their respective places.
|
||||
|
||||
# --hints--
|
||||
|
||||
`htmlColorNames` 应返回 `["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurqoise", "FireBrick"]`。
|
||||
`htmlColorNames` should return `["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurquoise", "FireBrick"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -50,19 +50,19 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`htmlColorNames` 函数中应调用 `splice()` 方法。
|
||||
The `htmlColorNames` function should utilize the `splice()` method
|
||||
|
||||
```js
|
||||
assert(/.splice/.test(code));
|
||||
```
|
||||
|
||||
不应使用 `shift()` 或 `unshift()`。
|
||||
You should not use `shift()` or `unshift()`.
|
||||
|
||||
```js
|
||||
assert(!/shift|unshift/.test(code));
|
||||
```
|
||||
|
||||
不应使用数组的方括号表示法。
|
||||
You should not use array bracket notation.
|
||||
|
||||
```js
|
||||
assert(!/\[\d\]\s*=/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b18
|
||||
title: 将键值对添加到对象中
|
||||
title: Add Key-Value Pairs to JavaScript Objects
|
||||
challengeType: 1
|
||||
forumTopicId: 301153
|
||||
dashedName: add-key-value-pairs-to-javascript-objects
|
||||
@ -8,7 +8,7 @@ dashedName: add-key-value-pairs-to-javascript-objects
|
||||
|
||||
# --description--
|
||||
|
||||
对象(object)本质上是<dfn>键值对(key-value pair)</dfn>的集合。或者说,一系列被映射到唯一标识符的数据就是对象;习惯上,唯一标识符叫做<dfn>属性(property)</dfn>或者<dfn>键(key)</dfn>);数据叫做<dfn>值(value)</dfn>。让我们来看一个简单的例子:
|
||||
At their most basic, objects are just collections of <dfn>key-value</dfn> pairs. In other words, they are pieces of data (<dfn>values</dfn>) mapped to unique identifiers called <dfn>properties</dfn> (<dfn>keys</dfn>). Take a look at an example:
|
||||
|
||||
```js
|
||||
const tekkenCharacter = {
|
||||
@ -18,19 +18,19 @@ const tekkenCharacter = {
|
||||
};
|
||||
```
|
||||
|
||||
上面的代码定义了一个叫做 `tekkenCharacter` 的“铁拳”游戏人物对象。它有三个属性,每个属性都对应一个特定的值。如果我们想为它再添加一个叫做 `origin` 的属性,可以这样写:
|
||||
The above code defines a Tekken video game character object called `tekkenCharacter`. It has three properties, each of which map to a specific value. If you want to add an additional property, such as "origin", it can be done by assigning `origin` to the object:
|
||||
|
||||
```js
|
||||
tekkenCharacter.origin = 'South Korea';
|
||||
```
|
||||
|
||||
上面的代码中,我们使用了<dfn>点号表示法(dot notation)</dfn>。如果我们现在输出这个对象,便可以看到它具有 `origin` 属性。接下来,因为这个人物在游戏中有着与众不同的橘色头发,我们可以通过方括号表示法来为它添加这个属性,像这样:
|
||||
This uses dot notation. If you were to observe the `tekkenCharacter` object, it will now include the `origin` property. Hwoarang also had distinct orange hair. You can add this property with bracket notation by doing:
|
||||
|
||||
```js
|
||||
tekkenCharacter['hair color'] = 'dyed orange';
|
||||
```
|
||||
|
||||
如果要设置的属性中存在空格,或者要设置的属性是一个变量,那我们必须使用<dfn>方括号表示法(bracket notation)</dfn>来为对象添加属性。在上面的代码中,我们把属性 `hair color` 放到引号里,以此来表示整个字符串都是需要设置的属性。如果我们不加上引号,那么中括号里的内容会被当作一个变量来解析,这个变量对应的值就会作为要设置的属性,请看这段代码:
|
||||
Bracket notation is required if your property has a space in it or if you want to use a variable to name the property. In the above case, the property is enclosed in quotes to denote it as a string and will be added exactly as shown. Without quotes, it will be evaluated as a variable and the name of the property will be whatever value the variable is. Here's an example with a variable:
|
||||
|
||||
```js
|
||||
const eyes = 'eye color';
|
||||
@ -38,7 +38,7 @@ const eyes = 'eye color';
|
||||
tekkenCharacter[eyes] = 'brown';
|
||||
```
|
||||
|
||||
执行以上所有示例代码后,对象会变成这样:
|
||||
After adding all the examples, the object will look like this:
|
||||
|
||||
```js
|
||||
{
|
||||
@ -53,35 +53,35 @@ tekkenCharacter[eyes] = 'brown';
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经为你创建了 `foods` 对象。请使用上述任意语法,来为 `foods` 对象添加如下三个键值对:`bananas` 属性,值为 `13`;`grapes` 属性,值为 `35`;`strawberries` 属性,值为 `27`。
|
||||
A `foods` object has been created with three entries. Using the syntax of your choice, add three more entries to it: `bananas` with a value of `13`, `grapes` with a value of `35`, and `strawberries` with a value of `27`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`foods` 应为一个对象。
|
||||
`foods` should be an object.
|
||||
|
||||
```js
|
||||
assert(typeof foods === 'object');
|
||||
```
|
||||
|
||||
`foods` 应有一个值为 `13` 的 `"bananas"` 属性。
|
||||
The `foods` object should have a key `"bananas"` with a value of `13`.
|
||||
|
||||
```js
|
||||
assert(foods.bananas === 13);
|
||||
```
|
||||
|
||||
`foods` 应有一个值为 `35` 的 `"grapes"` 属性。
|
||||
The `foods` object should have a key `"grapes"` with a value of `35`.
|
||||
|
||||
```js
|
||||
assert(foods.grapes === 35);
|
||||
```
|
||||
|
||||
`foods` 应有一个值为 `27` 的 `"strawberries"` 属性。
|
||||
The `foods` object should have a key `"strawberries"` with a value of `27`.
|
||||
|
||||
```js
|
||||
assert(foods.strawberries === 27);
|
||||
```
|
||||
|
||||
应使用点号表示法或方括号表示法来设置对象的属性。
|
||||
The key-value pairs should be set using dot or bracket notation.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b14
|
||||
title: 使用 indexOf() 检查元素是否存在
|
||||
title: Check For The Presence of an Element With indexOf()
|
||||
challengeType: 1
|
||||
forumTopicId: 301154
|
||||
dashedName: check-for-the-presence-of-an-element-with-indexof
|
||||
@ -8,25 +8,31 @@ dashedName: check-for-the-presence-of-an-element-with-indexof
|
||||
|
||||
# --description--
|
||||
|
||||
由于数组随时都可以修改或发生“突变”(*mutated*),我们很难保证某个数据始终处于数组中的特定位置,甚至不能保证该元素是否还存在于该数组中。好消息是,JavaScript 为我们提供了内置方法 `indexOf()`。这个方法让我们可以方便地检查某个元素是否存在于数组中。`indexOf()` 方法接受一个元素作为输入参数,并返回该元素在数组中的位置(索引);若该元素不存在于数组中则返回 `-1`。
|
||||
Since arrays can be changed, or *mutated*, at any time, there's no guarantee about where a particular piece of data will be on a given array, or if that element even still exists. Luckily, JavaScript provides us with another built-in method, `indexOf()`, that allows us to quickly and easily check for the presence of an element on an array. `indexOf()` takes an element as a parameter, and when called, it returns the position, or index, of that element, or `-1` if the element does not exist on the array.
|
||||
|
||||
例如:
|
||||
For example:
|
||||
|
||||
```js
|
||||
let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];
|
||||
|
||||
fruits.indexOf('dates'); // 返回 -1
|
||||
fruits.indexOf('oranges'); // 返回 2
|
||||
fruits.indexOf('pears'); // 返回 1,因为第一个出现在数组中的 'pears' 元素索引为 1
|
||||
fruits.indexOf('dates'); // returns -1
|
||||
fruits.indexOf('oranges'); // returns 2
|
||||
fruits.indexOf('pears'); // returns 1, the first index at which the element exists
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
`indexOf()` 在快速检查一个数组中是否存在某个元素时非常有用。我们已经定义了一个 `quickCheck` 函数,它接受一个数组和一个元素作为输入参数。请修改这个函数,通过 `indexOf()` 方法,使得当参数数组中包含第二个参数的元素时返回 `true`,不包含时返回 `false`。
|
||||
`indexOf()` can be incredibly useful for quickly checking for the presence of an element on an array. We have defined a function, `quickCheck`, that takes an array and an element as arguments. Modify the function using `indexOf()` so that it returns `true` if the passed element exists on the array, and `false` if it does not.
|
||||
|
||||
# --hints--
|
||||
|
||||
`quickCheck(["squash", "onions", "shallots"], "mushrooms")` 应返回 `false`。
|
||||
The `quickCheck` function should return a boolean (`true` or `false`), not a string (`"true"` or `"false"`)
|
||||
|
||||
```js
|
||||
assert.isBoolean(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
|
||||
```
|
||||
|
||||
`quickCheck(["squash", "onions", "shallots"], "mushrooms")` should return `false`
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -35,7 +41,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`quickCheck(["squash", "onions", "shallots"], "onions")` 应返回 `true`。
|
||||
`quickCheck(["onions", "squash", "shallots"], "onions")` should return `true`
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -44,19 +50,19 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`quickCheck([3, 5, 9, 125, 45, 2], 125)` 应返回 `true`。
|
||||
`quickCheck([3, 5, 9, 125, 45, 2], 125)` should return `true`
|
||||
|
||||
```js
|
||||
assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true);
|
||||
```
|
||||
|
||||
`quickCheck([true, false, false], undefined)` 应返回 `false`。
|
||||
`quickCheck([true, false, false], undefined)` should return `false`
|
||||
|
||||
```js
|
||||
assert.strictEqual(quickCheck([true, false, false], undefined), false);
|
||||
```
|
||||
|
||||
`quickCheck` 函数中应使用 `indexOf()` 方法。
|
||||
The `quickCheck` function should utilize the `indexOf()` method
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1c
|
||||
title: 检查对象是否具有某个属性
|
||||
title: Check if an Object has a Property
|
||||
challengeType: 1
|
||||
forumTopicId: 301155
|
||||
dashedName: check-if-an-object-has-a-property
|
||||
@ -8,21 +8,21 @@ dashedName: check-if-an-object-has-a-property
|
||||
|
||||
# --description--
|
||||
|
||||
我们已经学习了如果添加、修改和移除对象中的属性。但如果我们想知道一个对象中是否包含某个属性呢?JavaScript 为我们提供了两种不同的方式来实现这个功能:一个是通过 `hasOwnProperty()` 方法,另一个是使用 `in` 关键字。假如我们有一个 `users` 对象,为检查它是否含有 `Alan` 属性,可以这样写:
|
||||
Now we can add, modify, and remove keys from objects. But what if we just wanted to know if an object has a specific property? JavaScript provides us with two different ways to do this. One uses the `hasOwnProperty()` method and the other uses the `in` keyword. If we have an object `users` with a property of `Alan`, we could check for its presence in either of the following ways:
|
||||
|
||||
```js
|
||||
users.hasOwnProperty('Alan');
|
||||
'Alan' in users;
|
||||
// 都返回 true
|
||||
// both return true
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个包含若干用户信息的 `users` 对象和一个 `isEveryoneHere` 函数,该函数接收 `users` 对象作为参数。请完成该函数使其在 `users` 对象中同时包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 四个属性时才返回 `true`,否则返回 `false`。
|
||||
We've created an object, `users`, with some users in it and a function `isEveryoneHere`, which we pass the `users` object to as an argument. Finish writing this function so that it returns `true` only if the `users` object contains all four names, `Alan`, `Jeff`, `Sarah`, and `Ryan`, as keys, and `false` otherwise.
|
||||
|
||||
# --hints--
|
||||
|
||||
`users` 对象应该只包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 4 个属性。
|
||||
The `users` object should only contain the keys `Alan`, `Jeff`, `Sarah`, and `Ryan`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -34,13 +34,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`isEveryoneHere` 函数在 `users` 对象包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 4 个属性时应返回 `true`。
|
||||
The function `isEveryoneHere` should return `true` if `Alan`, `Jeff`, `Sarah`, and `Ryan` are properties on the `users` object
|
||||
|
||||
```js
|
||||
assert(isEveryoneHere(users) === true);
|
||||
```
|
||||
|
||||
`isEveryoneHere` 函数在 `users` 对象不包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 4 个属性时应返回 `false`。
|
||||
The function `isEveryoneHere` should return `false` if `Alan` is not a property on the `users` object
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -51,7 +51,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
如果 `users` 对象中不包含属性 `Jeff`,则函数 `isEveryoneHere` 应返回 `false`。
|
||||
The function `isEveryoneHere` should return `false` if `Jeff` is not a property on the `users` object
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -62,7 +62,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
如果 `users` 对象中不包含属性 `Sarah`,则函数 `isEveryoneHere` 应返回 `false`。
|
||||
The function `isEveryoneHere` should return `false` if `Sarah` is not a property on the `users` object
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -73,7 +73,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
如果 `users` 对象中不包含属性 `Ryan`,则函数 `isEveryoneHere` 应返回 `false`。
|
||||
The function `isEveryoneHere` should return `false` if `Ryan` is not a property on the `users` object
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b17
|
||||
title: 使用展开运算符合并数组
|
||||
title: Combine Arrays with the Spread Operator
|
||||
challengeType: 1
|
||||
forumTopicId: 301156
|
||||
dashedName: combine-arrays-with-the-spread-operator
|
||||
@ -8,30 +8,30 @@ dashedName: combine-arrays-with-the-spread-operator
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>展开语法</dfn>的另一个重要用途是合并数组,或者将某个数组的所有元素插入到另一个数组的任意位置。我们也可以使用 ES5 的语法连接两个数组,但只能让它们首尾相接。而展开语法可以让这样的操作变得极其简单:
|
||||
Another huge advantage of the <dfn>spread</dfn> operator, is the ability to combine arrays, or to insert all the elements of one array into another, at any index. With more traditional syntaxes, we can concatenate arrays, but this only allows us to combine arrays at the end of one, and at the start of another. Spread syntax makes the following operation extremely simple:
|
||||
|
||||
```js
|
||||
let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];
|
||||
|
||||
let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander'];
|
||||
// thatArray 现在是 ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']
|
||||
// thatArray now equals ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']
|
||||
```
|
||||
|
||||
使用展开语法,我们像这样就可以实现一个用传统方法会写得很复杂且冗长的操作。
|
||||
Using spread syntax, we have just achieved an operation that would have been more complex and more verbose had we used traditional methods.
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个返回 `sentence` 变量的 `spreadOut` 函数。请修改这个函数,利用<dfn>展开语法</dfn>使该函数返回数组 `['learning', 'to', 'code', 'is', 'fun']`。
|
||||
We have defined a function `spreadOut` that returns the variable `sentence`. Modify the function using the <dfn>spread</dfn> operator so that it returns the array `['learning', 'to', 'code', 'is', 'fun']`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`spreadOut` 应返回 `["learning", "to", "code", "is", "fun"]`。
|
||||
`spreadOut` should return `["learning", "to", "code", "is", "fun"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(spreadOut(), ['learning', 'to', 'code', 'is', 'fun']);
|
||||
```
|
||||
|
||||
`spreadOut` 函数里应用到展开语法。
|
||||
The `spreadOut` function should utilize spread syntax
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(spreadOut.toString().search(/[...]/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b13
|
||||
title: 使用展开运算符复制数组
|
||||
title: Copy an Array with the Spread Operator
|
||||
challengeType: 1
|
||||
forumTopicId: 301157
|
||||
dashedName: copy-an-array-with-the-spread-operator
|
||||
@ -8,24 +8,24 @@ dashedName: copy-an-array-with-the-spread-operator
|
||||
|
||||
# --description--
|
||||
|
||||
`slice()` 可以让我们从一个数组中选择一些元素来复制到新数组中,而 ES6 中又引入了一个简洁且可读性强的语法:<dfn>展开运算符(spread operator)</dfn>,它能让我们方便地复制数组中的*所有*元素。展开语法写出来是这样:`...`
|
||||
While `slice()` allows us to be selective about what elements of an array to copy, among several other useful tasks, ES6's new <dfn>spread operator</dfn> allows us to easily copy *all* of an array's elements, in order, with a simple and highly readable syntax. The spread syntax simply looks like this: `...`
|
||||
|
||||
我们可以用展开运算符来复制数组:
|
||||
In practice, we can use the spread operator to copy an array like so:
|
||||
|
||||
```js
|
||||
let thisArray = [true, true, undefined, false, null];
|
||||
let thatArray = [...thisArray];
|
||||
// thatArray 的值现在也是 [true, true, undefined, false, null]
|
||||
// thisArray 保持不变。现在 thatArray 所包含的值与 thisArray 完全相同
|
||||
// thatArray equals [true, true, undefined, false, null]
|
||||
// thisArray remains unchanged and thatArray contains the same elements as thisArray
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个 `copyMachine` 函数,它接受 `arr`(一个数组)和 `num`(一个数字)作为输入参数。该函数需要返回一个由 `num` 个 `arr` 组成的新的二维数组。同时,我们写好了大致的流程,只是细节实现还没有写完。请修改这个函数,使用展开语法,使该函数能正常工作(提示:我们已经学到过的一个方法很适合用在这里)!
|
||||
We have defined a function, `copyMachine` which takes `arr` (an array) and `num` (a number) as arguments. The function is supposed to return a new array made up of `num` copies of `arr`. We have done most of the work for you, but it doesn't work quite right yet. Modify the function using spread syntax so that it works correctly (hint: another method we have already covered might come in handy here!).
|
||||
|
||||
# --hints--
|
||||
|
||||
`copyMachine([true, false, true], 2)` 应返回 `[[true, false, true], [true, false, true]]`。
|
||||
`copyMachine([true, false, true], 2)` should return `[[true, false, true], [true, false, true]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([true, false, true], 2), [
|
||||
@ -34,7 +34,7 @@ assert.deepEqual(copyMachine([true, false, true], 2), [
|
||||
]);
|
||||
```
|
||||
|
||||
`copyMachine([1, 2, 3], 5)` 应返回 `[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]`。
|
||||
`copyMachine([1, 2, 3], 5)` should return `[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([1, 2, 3], 5), [
|
||||
@ -46,13 +46,13 @@ assert.deepEqual(copyMachine([1, 2, 3], 5), [
|
||||
]);
|
||||
```
|
||||
|
||||
`copyMachine([true, true, null], 1)` 应返回 `[[true, true, null]]`。
|
||||
`copyMachine([true, true, null], 1)` should return `[[true, true, null]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]]);
|
||||
```
|
||||
|
||||
`copyMachine(["it works"], 3)` 应返回 `[["it works"], ["it works"], ["it works"]]`。
|
||||
`copyMachine(["it works"], 3)` should return `[["it works"], ["it works"], ["it works"]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine(['it works'], 3), [
|
||||
@ -62,10 +62,10 @@ assert.deepEqual(copyMachine(['it works'], 3), [
|
||||
]);
|
||||
```
|
||||
|
||||
`copyMachine` 函数中应对 `arr` 使用`展开运算符`。
|
||||
The `copyMachine` function should utilize the `spread operator` with array `arr`
|
||||
|
||||
```js
|
||||
assert(removeJSComments(code).match(/\.\.\.arr/));
|
||||
assert(__helpers.removeJSComments(code).match(/\.\.\.arr/));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7a367417b2b2512b12
|
||||
title: 使用 slice() 复制数组元素
|
||||
title: Copy Array Items Using slice()
|
||||
challengeType: 1
|
||||
forumTopicId: 301158
|
||||
dashedName: copy-array-items-using-slice
|
||||
@ -8,25 +8,25 @@ dashedName: copy-array-items-using-slice
|
||||
|
||||
# --description--
|
||||
|
||||
接下来我们要介绍 `slice()` 方法。`slice()` 不会修改数组,而是会复制,或者说*提取(extract)*给定数量的元素到一个新数组。同时,调用方法的数组保持不变。`slice()` 只接收 2 个输入参数:第一个是开始提取元素的位置(索引),第二个是提取元素的结束位置(索引)。`slice()` 提取的元素中不包括第二个参数所对应的元素。请看以下例子:
|
||||
The next method we will cover is `slice()`. Rather than modifying an array, `slice()` copies or *extracts* a given number of elements to a new array, leaving the array it is called upon untouched. `slice()` takes only 2 parameters — the first is the index at which to begin extraction, and the second is the index at which to stop extraction (extraction will occur up to, but not including the element at this index). Consider this:
|
||||
|
||||
```js
|
||||
let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
|
||||
|
||||
let todaysWeather = weatherConditions.slice(1, 3);
|
||||
// todaysWeather 等于 ['snow', 'sleet'];
|
||||
// weatherConditions 仍然等于 ['rain', 'snow', 'sleet', 'hail', 'clear']
|
||||
// todaysWeather equals ['snow', 'sleet'];
|
||||
// weatherConditions still equals ['rain', 'snow', 'sleet', 'hail', 'clear']
|
||||
```
|
||||
|
||||
在上面的代码中,我们从一个数组中提取了一些元素,并用这些元素创建了一个新数组。
|
||||
In effect, we have created a new array by extracting elements from an existing array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个 `forecast` 函数,它接受一个数组作为参数。请修改这个函数,利用 `slice()` 从输入的数组中提取信息,最终返回一个包含元素 `'warm'` 和 `'sunny'` 的新数组。
|
||||
We have defined a function, `forecast`, that takes an array as an argument. Modify the function using `slice()` to extract information from the argument array and return a new array that contains the elements `'warm'` and `'sunny'`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`forecast` 应返回 `["warm", "sunny"]`。
|
||||
`forecast` should return `["warm", "sunny"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -35,7 +35,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`forecast` 函数中应使用 `slice()` 方法。
|
||||
The `forecast` function should utilize the `slice()` method
|
||||
|
||||
```js
|
||||
assert(/\.slice\(/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b16
|
||||
title: 创建复杂的多维数组
|
||||
title: Create complex multi-dimensional arrays
|
||||
challengeType: 1
|
||||
forumTopicId: 301159
|
||||
dashedName: create-complex-multi-dimensional-arrays
|
||||
@ -8,37 +8,37 @@ dashedName: create-complex-multi-dimensional-arrays
|
||||
|
||||
# --description--
|
||||
|
||||
很好!你现在已经学到很多关于数组的知识了,但这些只是个开始。我们将在接下来的中挑战中学到更多与数组相关的知识。在继续学习<dfn>对象</dfn>(<dfn>Objects</dfn>)之前,让我们再花一点时间了解下更复杂的数组嵌套。
|
||||
Awesome! You have just learned a ton about arrays! This has been a fairly high level overview, and there is plenty more to learn about working with arrays, much of which you will see in later sections. But before moving on to looking at <dfn>Objects</dfn>, lets take one more look, and see how arrays can become a bit more complex than what we have seen in previous challenges.
|
||||
|
||||
数组的一个强大的特性是,它可以包含其他数组,甚至完全由其他数组组成。在上一个挑战中,我们已经接触到了包含数组的数组,但它还算是比较简单的。数组中的数组还可以再包含其他数组,即可以嵌套任意多层数组。习惯上,我们称这种数据结构为<dfn>多维(multi-dimensional)数组</dfn>或嵌套(nested)数组。请看如下的示例:
|
||||
One of the most powerful features when thinking of arrays as data structures, is that arrays can contain, or even be completely made up of other arrays. We have seen arrays that contain arrays in previous challenges, but fairly simple ones. However, arrays can contain an infinite depth of arrays that can contain other arrays, each with their own arbitrary levels of depth, and so on. In this way, an array can very quickly become very complex data structure, known as a <dfn>multi-dimensional</dfn>, or nested array. Consider the following example:
|
||||
|
||||
```js
|
||||
let nestedArray = [ // 顶层,或第 1 层,即最外层数组
|
||||
['deep'], // 数组中的数组,第 2 层
|
||||
let nestedArray = [ // top, or first level - the outer most array
|
||||
['deep'], // an array within an array, 2 levels of depth
|
||||
[
|
||||
['deeper'], ['deeper'] // 第 3 层,元素为嵌套的两个数组
|
||||
['deeper'], ['deeper'] // 2 arrays nested 3 levels deep
|
||||
],
|
||||
[
|
||||
[
|
||||
['deepest'], ['deepest'] // 第 4 层,元素为嵌套的两个数组
|
||||
['deepest'], ['deepest'] // 2 arrays nested 4 levels deep
|
||||
],
|
||||
[
|
||||
[
|
||||
['deepest-est?'] // 第 5 层,元素为嵌套的一个数组
|
||||
['deepest-est?'] // an array nested 5 levels deep
|
||||
]
|
||||
]
|
||||
]
|
||||
];
|
||||
```
|
||||
|
||||
虽然这个例子看起来错综复杂,不过,尤其是在处理大量数据的时候,这种数据结构还是经常会用到的。尽管结构复杂,不过我们仍可以通过方括号表示法来访问嵌套得最深的数组:
|
||||
While this example may seem convoluted, this level of complexity is not unheard of, or even unusual, when dealing with large amounts of data. However, we can still very easily access the deepest levels of an array this complex with bracket notation:
|
||||
|
||||
```js
|
||||
console.log(nestedArray[2][1][0][0][0]);
|
||||
// logs: deepest-est?
|
||||
```
|
||||
|
||||
既然我们知道数据的位置,当然,我们也可以修改它:
|
||||
And now that we know where that piece of data is, we can reset it if we need to:
|
||||
|
||||
```js
|
||||
nestedArray[2][1][0][0][0] = 'deeper still';
|
||||
@ -49,11 +49,11 @@ console.log(nestedArray[2][1][0][0][0]);
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个叫做 `myNestedArray` 的数组变量。请修改 `myNestedArray`,使用<dfn>字符串(string)</dfn>、<dfn>数字(number)</dfn>或<dfn>布尔值(boolean)</dfn>作为数组的元素,并让 `myNestedArray` 刚好有 5 层(注意,最外层的数组是第 1 层)。同时,请在第 3 层的数组中包含字符串 `'deep'`;在第 4 层的数组中包含字符串 `'deeper'`,在第 5 层的数组中包含字符串 `'deepest'`。
|
||||
We have defined a variable, `myNestedArray`, set equal to an array. Modify `myNestedArray`, using any combination of <dfn>strings</dfn>, <dfn>numbers</dfn>, and <dfn>booleans</dfn> for data elements, so that it has exactly five levels of depth (remember, the outer-most array is level 1). Somewhere on the third level, include the string `'deep'`, on the fourth level, include the string `'deeper'`, and on the fifth level, include the string `'deepest'`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myNestedArray` 中的数据元素应只包含字符串、数字或者布尔值。
|
||||
`myNestedArray` should contain only numbers, booleans, and strings as data elements
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -77,7 +77,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` 应刚好包含 5 层嵌套数组。
|
||||
`myNestedArray` should have exactly 5 levels of depth
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -100,7 +100,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` 中应只有一个字符串 `"deep"`,并且应出现在第 3 层数组中。
|
||||
`myNestedArray` should contain exactly one occurrence of the string `"deep"` on an array nested 3 levels deep
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -129,7 +129,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` 中应只有一个字符串 `"deeper"`,并且应出现在第 4 层数组中。
|
||||
`myNestedArray` should contain exactly one occurrence of the string `"deeper"` on an array nested 4 levels deep
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -158,7 +158,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` 中应只有一个字符串 `"deepest"`,并且应出现在第 5 层数组中。
|
||||
`myNestedArray` should contain exactly one occurrence of the string `"deepest"` on an array nested 5 levels deep
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1e
|
||||
title: 使用 Object.keys() 生成由对象的所有属性组成的数组
|
||||
title: Generate an Array of All Object Keys with Object.keys()
|
||||
challengeType: 1
|
||||
forumTopicId: 301160
|
||||
dashedName: generate-an-array-of-all-object-keys-with-object-keys
|
||||
@ -8,15 +8,15 @@ dashedName: generate-an-array-of-all-object-keys-with-object-keys
|
||||
|
||||
# --description--
|
||||
|
||||
我们可以给 `Object.keys()` 方法传入一个对象作为参数,这会返回一个由对象中所有属性(字符串)组成的数组。需要注意的是,数组中元素的顺序是不确定的。
|
||||
We can also generate an array which contains all the keys stored in an object using the `Object.keys()` method and passing in an object as the argument. This will return an array with strings representing each property in the object. Again, there will be no specific order to the entries in the array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
请完成 `getArrayOfUsers` 函数的实现,使其返回一个由输入对象中的所有属性所组成的数组。
|
||||
Finish writing the `getArrayOfUsers` function so that it returns an array containing all the properties in the object it receives as an argument.
|
||||
|
||||
# --hints--
|
||||
|
||||
`users` 对象应该只包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 这 4 个属性。
|
||||
The `users` object should only contain the keys `Alan`, `Jeff`, `Sarah`, and `Ryan`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -28,7 +28,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`getArrayOfUsers` 函数应返回一个包含 `users` 对象中所有属性的数组。
|
||||
The `getArrayOfUsers` function should return an array which contains all the keys in the `users` object
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b15
|
||||
title: 使用 for 循环遍历数组中的全部元素
|
||||
title: Iterate Through All an Array's Items Using For Loops
|
||||
challengeType: 1
|
||||
forumTopicId: 301161
|
||||
dashedName: iterate-through-all-an-arrays-items-using-for-loops
|
||||
@ -8,9 +8,9 @@ dashedName: iterate-through-all-an-arrays-items-using-for-loops
|
||||
|
||||
# --description--
|
||||
|
||||
使用数组时,我们经常需要遍历数组的所有元素来找出我们需要的一个或多个元素,抑或是对数组执行一些特定的操作。JavaScript 为我们提供了几个内置的方法,它们以不同的方式遍历数组,以便我们可以用于不同的场景(如 `every()`、`forEach()`、`map()` 等等)。然而,最简单的 `for` 循环不仅能实现上述这些方法的功能,而且相比之下也会更加灵活。
|
||||
Sometimes when working with arrays, it is very handy to be able to iterate through each item to find one or more elements that we might need, or to manipulate an array based on which data items meet a certain set of criteria. JavaScript offers several built in methods that each iterate over arrays in slightly different ways to achieve different results (such as `every()`, `forEach()`, `map()`, etc.), however the technique which is most flexible and offers us the greatest amount of control is a simple `for` loop.
|
||||
|
||||
请看以下的例子:
|
||||
Consider the following:
|
||||
|
||||
```js
|
||||
function greaterThanTen(arr) {
|
||||
@ -24,18 +24,18 @@ function greaterThanTen(arr) {
|
||||
}
|
||||
|
||||
greaterThanTen([2, 12, 8, 14, 80, 0, 1]);
|
||||
// 返回 [12, 14, 80]
|
||||
// returns [12, 14, 80]
|
||||
```
|
||||
|
||||
在这个函数中,我们用一个 `for` 循环来遍历数组,逐一对其中的元素进行判断。通过上面的代码,我们可以找出数组中大于 `10` 的所有元素,并返回一个包含这些元素的新数组。
|
||||
Using a `for` loop, this function iterates through and accesses each element of the array, and subjects it to a simple test that we have created. In this way, we have easily and programmatically determined which data items are greater than `10`, and returned a new array containing those items.
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了 `filteredArray` 函数,它接受一个嵌套的数组 `arr` 和一个 `elem` 作为参数,并要返回一个新数组。`arr` 数组中嵌套的数组里可能包含 `elem` 元素,也可能不包含。请修改该函数,用一个 `for` 循环来做筛选,使函数返回一个由 `arr` 中不包含 `elem` 的数组所组成的新数组。
|
||||
We have defined a function, `filteredArray`, which takes `arr`, a nested array, and `elem` as arguments, and returns a new array. `elem` represents an element that may or may not be present on one or more of the arrays nested within `arr`. Modify the function, using a `for` loop, to return a filtered version of the passed array such that any array nested within `arr` containing `elem` has been removed.
|
||||
|
||||
# --hints--
|
||||
|
||||
`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` 应返回 `[ [10, 8, 3], [14, 6, 23] ]`。
|
||||
`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` should return `[ [10, 8, 3], [14, 6, 23] ]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -54,7 +54,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2)` 应返回 `[ ["flutes", 4] ]`。
|
||||
`filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2)` should return `[ ["flutes", 4] ]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -70,7 +70,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")` 应返回 `[ ["amy", "beth", "sam"] ]`。
|
||||
`filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")` should return `[ ["amy", "beth", "sam"] ]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -85,7 +85,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` 应返回 `[]`。
|
||||
`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` should return `[ ]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -102,7 +102,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray` 函数中应使用 `for` 循环。
|
||||
The `filteredArray` function should utilize a `for` loop
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(filteredArray.toString().search(/for/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1d
|
||||
title: 使用 for...in 语句遍历对象
|
||||
title: Iterate Through the Keys of an Object with a for...in Statement
|
||||
challengeType: 1
|
||||
forumTopicId: 301162
|
||||
dashedName: iterate-through-the-keys-of-an-object-with-a-for---in-statement
|
||||
@ -8,25 +8,25 @@ dashedName: iterate-through-the-keys-of-an-object-with-a-for---in-statement
|
||||
|
||||
# --description--
|
||||
|
||||
如果我们想要遍历对象中的所有属性,只需要使用 JavaScript 中的 <dfn>for...in</dfn> 语句即可。以遍历 `users` 对象的属性为例:
|
||||
Sometimes you may need to iterate through all the keys within an object. This requires a specific syntax in JavaScript called a <dfn>for...in</dfn> statement. For our `users` object, this could look like:
|
||||
|
||||
```js
|
||||
for (let user in users) {
|
||||
console.log(user);
|
||||
}
|
||||
|
||||
// 输出:
|
||||
// logs:
|
||||
Alan
|
||||
Jeff
|
||||
Sarah
|
||||
Ryan
|
||||
```
|
||||
|
||||
在上面的代码中,我们定义了一个 `user` 变量。可以观察到,这个变量在遍历对象的 `for...in` 语句执行过程中会一直被重置并赋予新值,结果就是不同的用户名打印到了 console 中。**注意:**对象中的键是无序的,这与数组不同。因此,一个对象中某个属性的位置,或者说它出现的相对顺序,在引用或访问该属性时是不确定的。
|
||||
In this statement, we defined a variable `user`, and as you can see, this variable was reset during each iteration to each of the object's keys as the statement looped through the object, resulting in each user's name being printed to the console. **NOTE:** Objects do not maintain an ordering to stored keys like arrays do; thus a key's position on an object, or the relative order in which it appears, is irrelevant when referencing or accessing that key.
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个 `countOnline` 函数,请在其中使用 <dfn>for...in</dfn> 语句来遍历 `users` 对象中的用户,并返回 `online` 属性为 `true` 的用户数量。以下是一个传入 `countOnline` 函数的对象示例,注意每个用户都有 `online` 属性,其属性值为 `true` 或 `false`:
|
||||
We've defined a function `countOnline` which accepts one argument (a users object). Use a <dfn>for...in</dfn> statement within this function to loop through the users object passed into the function and return the number of users whose `online` property is set to `true`. An example of a users object which could be passed to `countOnline` is shown below. Each user will have an `online` property with either a `true` or `false` value.
|
||||
|
||||
```js
|
||||
{
|
||||
@ -44,29 +44,29 @@ Ryan
|
||||
|
||||
# --hints--
|
||||
|
||||
函数 `countOnline` 中应使用 `for in` 语句遍历传入的对象。
|
||||
The function `countOnline` should use a `for in` statement to iterate through the object keys of the object passed to it.
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(
|
||||
/for\s*\(\s*(var|let)\s+[a-zA-Z_$]\w*\s+in\s+[a-zA-Z_$]\w*\s*\)\s*{/
|
||||
/for\s*\(\s*(var|let|const)\s+[a-zA-Z_$]\w*\s+in\s+[a-zA-Z_$]\w*\s*\)/
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
当传入 `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }` 时,函数 `countOnline` 应该返回 `1`。
|
||||
The function `countOnline` should return `1` when the object `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }` is passed to it
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj1) === 1);
|
||||
```
|
||||
|
||||
当传入 `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }` 时,函数 `countOnline` 应该返回 `2`。
|
||||
The function `countOnline` should return `2` when the object `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }` is passed to it
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj2) === 2);
|
||||
```
|
||||
|
||||
当传入 `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }` 时,函数 `countOnline` 应该返回 `0`。
|
||||
The function `countOnline` should return `0` when the object `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }` is passed to it
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj3) === 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1f
|
||||
title: 修改存储在对象中的数组
|
||||
title: Modify an Array Stored in an Object
|
||||
challengeType: 1
|
||||
forumTopicId: 301163
|
||||
dashedName: modify-an-array-stored-in-an-object
|
||||
@ -8,21 +8,21 @@ dashedName: modify-an-array-stored-in-an-object
|
||||
|
||||
# --description--
|
||||
|
||||
我们已经学习了 JavaScript 对象的这些基本操作:添加、修改、移除键值对、检查某个属性是否存在、遍历对象的所有属性。在继续学习 JavaScript 的过程中,我们会了解对象的更多用法。另外,在之后的数据结构课程中,我们还会学习 ES6 的 <dfn>Map</dfn> 和 <dfn>Set</dfn>。这两种数据结构与我们现在学到的对象十分类似,但它们在对象的基础上提供了一些额外的功能。目前,我们已经学习了数组和对象的基础知识,让我们试着来用所学的知识解决一些更复杂的问题。
|
||||
Now you've seen all the basic operations for JavaScript objects. You can add, modify, and remove key-value pairs, check if keys exist, and iterate over all the keys in an object. As you continue learning JavaScript you will see even more versatile applications of objects. Additionally, the Data Structures lessons located in the Coding Interview Prep section of the curriculum also cover the ES6 <dfn>Map</dfn> and <dfn>Set</dfn> objects, both of which are similar to ordinary objects but provide some additional features. Now that you've learned the basics of arrays and objects, you're fully prepared to begin tackling more complex problems using JavaScript!
|
||||
|
||||
# --instructions--
|
||||
|
||||
请看一下代码编辑器中我们为你写好的对象。`user` 对象包含 3 个属性;`data` 对象包含 5 个属性,其中包含一个叫做 `friends` 的数组。这就是对象作为数据结构所展现出的灵活性。我们已经写好了 `addFriend` 函数的一部分,请你完成这个函数,使其接受一个 `user` 对象,将 `friend` 参数中的名字添加到 `user.data.friends` 数组中并返回该数组。
|
||||
Take a look at the object we've provided in the code editor. The `user` object contains three keys. The `data` key contains five keys, one of which contains an array of `friends`. From this, you can see how flexible objects are as data structures. We've started writing a function `addFriend`. Finish writing it so that it takes a `user` object and adds the name of the `friend` argument to the array stored in `user.data.friends` and returns that array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`user` 对象应该包含 `name`、`age` 和 `data` 三个属性。
|
||||
The `user` object should have `name`, `age`, and `data` keys.
|
||||
|
||||
```js
|
||||
assert('name' in user && 'age' in user && 'data' in user);
|
||||
```
|
||||
|
||||
`addFriend` 函数应该接受一个 `user` 对象和一个 `friend` 字符串作为输入参数,并将这个字符串插入到 `user` 对象的 `friends` 数组中。
|
||||
The `addFriend` function should accept a `user` object and a `friend` string as arguments and add the friend to the array of `friends` in the `user` object.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -35,7 +35,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`addFriend(user, "Pete")` 应该返回 `["Sam", "Kira", "Tomo", "Pete"]`。
|
||||
`addFriend(user, "Pete")` should return `["Sam", "Kira", "Tomo", "Pete"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b19
|
||||
title: 修改嵌套在对象中的对象
|
||||
title: Modify an Object Nested Within an Object
|
||||
challengeType: 1
|
||||
forumTopicId: 301164
|
||||
dashedName: modify-an-object-nested-within-an-object
|
||||
@ -8,7 +8,7 @@ dashedName: modify-an-object-nested-within-an-object
|
||||
|
||||
# --description--
|
||||
|
||||
现在我们来看一个稍复杂的对象。在对象中,我们也可以嵌套任意层数的对象,对象的属性值可以是 JavaScript 支持的任意类型,包括数组和其他对象。请看以下例子:
|
||||
Now let's take a look at a slightly more complex object. Object properties can be nested to an arbitrary depth, and their values can be any type of data supported by JavaScript, including arrays and even other objects. Consider the following:
|
||||
|
||||
```js
|
||||
let nestedObject = {
|
||||
@ -19,13 +19,14 @@ let nestedObject = {
|
||||
online: 80,
|
||||
onlineStatus: {
|
||||
active: 67,
|
||||
away: 13
|
||||
away: 13,
|
||||
busy: 8
|
||||
}
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
`nestedObject` 有 3 个属性:`id`(属性值为数字)、`date`(属性值为字符串)、`data`(属性值为嵌套的对象)。虽然对象中的数据可能很复杂,我们仍能使用上一个挑战中讲到的写法来访问我们需要的信息。如果我们想把嵌套在 `onlineStatus` 中 `busy` 的属性值改为 `10`,可以用点号表示法来这样实现:
|
||||
`nestedObject` has three properties: `id` (value is a number), `date` (value is a string), and `data` (value is an object with its nested structure). While structures can quickly become complex, we can still use the same notations to access the information we need. To assign the value `10` to the `busy` property of the nested `onlineStatus` object, we use dot notation to reference the property:
|
||||
|
||||
```js
|
||||
nestedObject.data.onlineStatus.busy = 10;
|
||||
@ -33,11 +34,11 @@ nestedObject.data.onlineStatus.busy = 10;
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个 `userActivity` 对象,它包含了另一个对象。请将 `online` 的属性值改为 `45`。
|
||||
Here we've defined an object `userActivity`, which includes another object nested within it. Set the value of the `online` key to `45`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`userActivity` 应包含 `id`、`date` 和 `data` 属性。
|
||||
`userActivity` should have `id`, `date` and `data` properties.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -45,19 +46,19 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`userActivity` 应包含 `data` 属性,其属性值应为包含 `totalUsers` 和 `online` 属性的对象。
|
||||
`userActivity` should have a `data` key set to an object with keys `totalUsers` and `online`.
|
||||
|
||||
```js
|
||||
assert('totalUsers' in userActivity.data && 'online' in userActivity.data);
|
||||
```
|
||||
|
||||
`userActivity` 的 `data` 属性值中的 `online` 属性值应被改为 `45`。
|
||||
The `online` property nested in the `data` key of `userActivity` should be set to `45`
|
||||
|
||||
```js
|
||||
assert(userActivity.data.online === 45);
|
||||
```
|
||||
|
||||
应使用点号表示法或方括号表示法来修改 `online` 属性值。
|
||||
The `online` property should be set using dot or bracket notation.
|
||||
|
||||
```js
|
||||
assert.strictEqual(code.search(/online: 45/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b0f
|
||||
title: 使用 pop() 和 shift() 从数组中删除元素
|
||||
title: Remove Items from an Array with pop() and shift()
|
||||
challengeType: 1
|
||||
forumTopicId: 301165
|
||||
dashedName: remove-items-from-an-array-with-pop-and-shift
|
||||
@ -8,35 +8,35 @@ dashedName: remove-items-from-an-array-with-pop-and-shift
|
||||
|
||||
# --description--
|
||||
|
||||
`push()` 和 `unshift()` 都有一个与它们作用相反的函数:`pop()` 和 `shift()`。与插入元素相反,`pop()` 会从数组的末尾*移除*一个元素,而 `shift()` 会从数组的开头移除一个元素。`pop()` 和 `shift()` 与 `push()` 和 `unshift()` 的关键区别在于,用于删除元素的方法不接收参数,而且每次只能删除数组中的一个元素。
|
||||
Both `push()` and `unshift()` have corresponding methods that are nearly functional opposites: `pop()` and `shift()`. As you may have guessed by now, instead of adding, `pop()` *removes* an element from the end of an array, while `shift()` removes an element from the beginning. The key difference between `pop()` and `shift()` and their cousins `push()` and `unshift()`, is that neither method takes parameters, and each only allows an array to be modified by a single element at a time.
|
||||
|
||||
让我们来看以下的例子:
|
||||
Let's take a look:
|
||||
|
||||
```js
|
||||
let greetings = ['whats up?', 'hello', 'see ya!'];
|
||||
|
||||
greetings.pop();
|
||||
// 数组现在是 ['whats up?', 'hello']
|
||||
// now equals ['whats up?', 'hello']
|
||||
|
||||
greetings.shift();
|
||||
// 数组现在是 ['hello']
|
||||
// now equals ['hello']
|
||||
```
|
||||
|
||||
这些用于删除数组元素的方法会返回被删除的元素:
|
||||
We can also return the value of the removed element with either method like this:
|
||||
|
||||
```js
|
||||
let popped = greetings.pop();
|
||||
// 返回 'hello',即 popped 的值为 'hello'
|
||||
// greetings 数组现在为 []
|
||||
// returns 'hello'
|
||||
// greetings now equals []
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个 `popShift` 函数,它接收一个数组作为输入参数并返回一个新的数组。请修改这个函数,使用 `pop()` 和 `shift()` 来移除输入的数组中的第一个元素和最后一个元素,并将这两个被移除的元素分别赋值给对应的变量,使得最终返回的数组里包含这两个值。
|
||||
We have defined a function, `popShift`, which takes an array as an argument and returns a new array. Modify the function, using `pop()` and `shift()`, to remove the first and last elements of the argument array, and assign the removed elements to their corresponding variables, so that the returned array contains their values.
|
||||
|
||||
# --hints--
|
||||
|
||||
`popShift(["challenge", "is", "not", "complete"])` 应返回 `["challenge", "complete"]`。
|
||||
`popShift(["challenge", "is", "not", "complete"])` should return `["challenge", "complete"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [
|
||||
@ -45,13 +45,13 @@ assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [
|
||||
]);
|
||||
```
|
||||
|
||||
`popShift` 函数中应使用 `pop()` 方法。
|
||||
The `popShift` function should utilize the `pop()` method
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1);
|
||||
```
|
||||
|
||||
`popShift` 函数中应使用 `shift()` 方法。
|
||||
The `popShift` function should utilize the `shift()` method
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b10
|
||||
title: 使用 splice() 删除元素
|
||||
title: Remove Items Using splice()
|
||||
challengeType: 1
|
||||
forumTopicId: 301166
|
||||
dashedName: remove-items-using-splice
|
||||
@ -8,40 +8,42 @@ dashedName: remove-items-using-splice
|
||||
|
||||
# --description--
|
||||
|
||||
在之前的挑战中,我们已经学习了如何用 `shift()` 和 `pop()` 从数组的开头或末尾移除元素。但如果我们想删除数组中间的一个元素,或者想一次删除多个元素,该如何操作呢?这时候我们就需要使用 `splice()` 方法了,`splice()` 可以让我们从数组中的任意位置**连续删除任意数量的元素**。
|
||||
Ok, so we've learned how to remove elements from the beginning and end of arrays using `shift()` and `pop()`, but what if we want to remove an element from somewhere in the middle? Or remove more than one element at once? Well, that's where `splice()` comes in. `splice()` allows us to do just that: **remove any number of consecutive elements** from anywhere in an array.
|
||||
|
||||
`splice()` 最多可以接受 3 个参数,但现在我们先关注前两个。`splice()` 接收的前两个参数以调用 `splice()` 数组中的元素索引作为参考。别忘了,数组的索引是*从 0 开始的*,所以我们要用 `0` 来表示数组中的第一个元素。`splice()` 的第一个参数代表从数组中的哪个索引开始移除元素,而第二个参数表示要从数组中的这位位置删除多少个元素。例如:
|
||||
`splice()` can take up to 3 parameters, but for now, we'll focus on just the first 2. The first two parameters of `splice()` are integers which represent indexes, or positions, of the array that `splice()` is being called upon. And remember, arrays are *zero-indexed*, so to indicate the first element of an array, we would use `0`. `splice()`'s first parameter represents the index on the array from which to begin removing elements, while the second parameter indicates the number of elements to delete. For example:
|
||||
|
||||
```js
|
||||
let array = ['today', 'was', 'not', 'so', 'great'];
|
||||
|
||||
array.splice(2, 2);
|
||||
// 从索引为 2 的位置(即第三个元素)开始移除 2 个元素
|
||||
// array 的值现在是 ['today', 'was', 'great']
|
||||
// remove 2 elements beginning with the 3rd element
|
||||
// array now equals ['today', 'was', 'great']
|
||||
```
|
||||
|
||||
`splice()` 不仅会修改调用该方法的数组,还会返回一个包含被移除元素的数组:
|
||||
`splice()` not only modifies the array it's being called on, but it also returns a new array containing the value of the removed elements:
|
||||
|
||||
```js
|
||||
let array = ['I', 'am', 'feeling', 'really', 'happy'];
|
||||
|
||||
let newArray = array.splice(3, 2);
|
||||
// newArray 的值是 ['really', 'happy']
|
||||
// newArray equals ['really', 'happy']
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了数组 `arr`。请使用 `splice()` 从 `arr` 里移除元素,使剩余的元素之和为 `10`。
|
||||
We've initialized an array `arr`. Use `splice()` to remove elements from `arr`, so that it only contains elements that sum to the value of `10`.
|
||||
|
||||
# --hints--
|
||||
|
||||
不应修改这一行 `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`。
|
||||
You should not change the original line of `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`.
|
||||
|
||||
```js
|
||||
assert(code.replace(/\s/g, '').match(/constarr=\[2,4,5,1,7,5,2,1\];?/));
|
||||
assert(
|
||||
__helpers.removeWhiteSpace(code).match(/constarr=\[2,4,5,1,7,5,2,1\];?/)
|
||||
);
|
||||
```
|
||||
|
||||
`ahr` 的剩余元素之和应为 `10`。
|
||||
`arr` should only contain elements that sum to `10`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -50,16 +52,18 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
应对 `arr` 调用 `splice()` 方法。
|
||||
Your code should utilize the `splice()` method on `arr`.
|
||||
|
||||
```js
|
||||
assert(code.replace(/\s/g, '').match(/arr\.splice\(/));
|
||||
assert(__helpers.removeWhiteSpace(code).match(/arr\.splice\(/));
|
||||
```
|
||||
|
||||
splice 应只删除 `arr` 里面的元素,不能给 `arr` 添加元素。
|
||||
The splice should only remove elements from `arr` and not add any additional elements to `arr`.
|
||||
|
||||
```js
|
||||
assert(!code.replace(/\s/g, '').match(/arr\.splice\(\d+,\d+,\d+.*\)/g));
|
||||
assert(
|
||||
!__helpers.removeWhiteSpace(code).match(/arr\.splice\(\d+,\d+,\d+.*\)/g)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7e367417b2b2512b20
|
||||
title: 使用数组存储不同类型的数据
|
||||
title: Use an Array to Store a Collection of Data
|
||||
challengeType: 1
|
||||
forumTopicId: 301167
|
||||
dashedName: use-an-array-to-store-a-collection-of-data
|
||||
@ -8,15 +8,15 @@ dashedName: use-an-array-to-store-a-collection-of-data
|
||||
|
||||
# --description--
|
||||
|
||||
以下是最简单的<dfn>数组(Array)</dfn>示例:这是一个<dfn>一维数组(one-dimensional array)</dfn>,它只有一层,或者说它里面没有包含其它数组。可以观察到,这个数组中只包含了<dfn>布尔值(booleans)</dfn>、<dfn>字符串(strings)</dfn>、<dfn>数字(numbers)</dfn>以及 JavaScript 中的其他数据类型:
|
||||
The below is an example of the simplest implementation of an array data structure. This is known as a <dfn>one-dimensional array</dfn>, meaning it only has one level, or that it does not have any other arrays nested within it. Notice it contains <dfn>booleans</dfn>, <dfn>strings</dfn>, and <dfn>numbers</dfn>, among other valid JavaScript data types:
|
||||
|
||||
```js
|
||||
let simpleArray = ['one', 2, 'three', true, false, undefined, null];
|
||||
console.log(simpleArray.length);
|
||||
// 输出 7
|
||||
// logs 7
|
||||
```
|
||||
|
||||
所有数组都有一个表示长度的属性,我们可以通过 `Array.length` 来访问它。接下来是一个稍复杂的数组示例:这是一个<dfn>多维数组(multi-dimensional Array)</dfn>,或者说是一个包含了其他数组的数组。可以观察到,在这个数组内部还包含了 JavaScript 的<dfn>对象(objects)</dfn>,我们会在后面的挑战中详细讨论该数据结构。现在,你只需要知道数组能够存储复杂的对象数据。
|
||||
All arrays have a length property, which as shown above, can be very easily accessed with the syntax `Array.length`. A more complex implementation of an array can be seen below. This is known as a <dfn>multi-dimensional array</dfn>, or an array that contains other arrays. Notice that this array also contains JavaScript <dfn>objects</dfn>, which we will examine very closely in our next section, but for now, all you need to know is that arrays are also capable of storing complex objects.
|
||||
|
||||
```js
|
||||
let complexArray = [
|
||||
@ -45,35 +45,35 @@ let complexArray = [
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个名为 `yourArray` 的变量。请修改代码,将一个含有至少 5 个元素的数组赋值给 `yourArray` 变量。你的数组中应包含至少一个 <dfn>string</dfn> 类型的数据、一个 <dfn>number</dfn> 类型的数据和一个 <dfn>boolean</dfn> 类型的数据。
|
||||
We have defined a variable called `yourArray`. Complete the statement by assigning an array of at least 5 elements in length to the `yourArray` variable. Your array should contain at least one <dfn>string</dfn>, one <dfn>number</dfn>, and one <dfn>boolean</dfn>.
|
||||
|
||||
# --hints--
|
||||
|
||||
yourArray 应为数组。
|
||||
`yourArray` should be an array.
|
||||
|
||||
```js
|
||||
assert.strictEqual(Array.isArray(yourArray), true);
|
||||
```
|
||||
|
||||
`yourArray` 应包含至少 5 个元素。
|
||||
`yourArray` should be at least 5 elements long.
|
||||
|
||||
```js
|
||||
assert.isAtLeast(yourArray.length, 5);
|
||||
```
|
||||
|
||||
`yourArray` 应包含至少一个 `boolean`。
|
||||
`yourArray` should contain at least one `boolean`.
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'boolean').length >= 1);
|
||||
```
|
||||
|
||||
`yourArray` 应包含至少一个 `number`。
|
||||
`yourArray` should contain at least one `number`.
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'number').length >= 1);
|
||||
```
|
||||
|
||||
`yourArray` 应包含至少一个 `string`。
|
||||
`yourArray` should contain at least one `string`.
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'string').length >= 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b1b
|
||||
title: 使用 delete 关键字删除对象属性
|
||||
title: Use the delete Keyword to Remove Object Properties
|
||||
challengeType: 1
|
||||
forumTopicId: 301168
|
||||
dashedName: use-the-delete-keyword-to-remove-object-properties
|
||||
@ -8,11 +8,11 @@ dashedName: use-the-delete-keyword-to-remove-object-properties
|
||||
|
||||
# --description--
|
||||
|
||||
现在我们已经学习了什么是对象以及对象的基本特性和用途。总之,对象是以键值对的形式,灵活、直观地存储结构化数据的一种方式,***而且***,通过对象的属性查找属性值是速度很快的操作。在本章余下的挑战中,我们来了解一下对象的几种常用操作,这样你能更好地在代码中使用这个十分有用的数据结构:对象。
|
||||
Now you know what objects are and their basic features and advantages. In short, they are key-value stores which provide a flexible, intuitive way to structure data, ***and***, they provide very fast lookup time. Throughout the rest of these challenges, we will describe several common operations you can perform on objects so you can become comfortable applying these useful data structures in your programs.
|
||||
|
||||
在之前的挑战中,我们已经试过添加和修改对象中的键值对。现在我们来看看如何从一个对象中*移除*一个键值对。
|
||||
In earlier challenges, we have both added to and modified an object's key-value pairs. Here we will see how we can *remove* a key-value pair from an object.
|
||||
|
||||
我们再来回顾一下上一个挑战中的 `foods` 对象。如果我们想移除 `apples` 属性,可以像这样使用 `delete` 关键字:
|
||||
Let's revisit our `foods` object example one last time. If we wanted to remove the `apples` key, we can remove it by using the `delete` keyword like this:
|
||||
|
||||
```js
|
||||
delete foods.apples;
|
||||
@ -20,11 +20,11 @@ delete foods.apples;
|
||||
|
||||
# --instructions--
|
||||
|
||||
请使用 `delete` 关键字来移除 `foods` 中的 `oranges`、`plums` 和 `strawberries` 属性。
|
||||
Use the delete keyword to remove the `oranges`, `plums`, and `strawberries` keys from the `foods` object.
|
||||
|
||||
# --hints--
|
||||
|
||||
`foods` 对象应只包含 3 个属性:`apples`、`grapes` 和 `bananas`。
|
||||
The `foods` object should only have three keys: `apples`, `grapes`, and `bananas`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -35,7 +35,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
应使用 `delete` 关键字来移除 `oranges`、`plums` 和 `strawberries` 属性。
|
||||
The `oranges`, `plums`, and `strawberries` keys should be removed using `delete`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392ca
|
||||
title: 通过索引访问数组中的数据
|
||||
title: Access Array Data with Indexes
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBZQbTz'
|
||||
forumTopicId: 16158
|
||||
@ -9,28 +9,30 @@ dashedName: access-array-data-with-indexes
|
||||
|
||||
# --description--
|
||||
|
||||
我们可以使用索引(`indexes`)来访问数组中的数据。
|
||||
We can access the data inside arrays using <dfn>indexes</dfn>.
|
||||
|
||||
数组索引与字符串索引都需要通过方括号表示法使用。区别仅仅在于,字符串通过索引会得到一个字符,而数组通过索引得到的是一个元素。数组索引与字符串索引一样是从 0 开始的,所以数组中第一个元素的索引是 `0`。
|
||||
Array indexes are written in the same bracket notation that strings use, except that instead of specifying a character, they are specifying an entry in the array. Like strings, arrays use <dfn>zero-based</dfn> indexing, so the first element in an array has an index of `0`.
|
||||
|
||||
**示例**
|
||||
<br>
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
var array = [50,60,70];
|
||||
array[0]; // 返回 50
|
||||
var data = array[1]; // 值为 60
|
||||
array[0]; // equals 50
|
||||
var data = array[1]; // equals 60
|
||||
```
|
||||
|
||||
**注意**
|
||||
数组名与方括号之间不应有空格,不推荐像是 `array [0]` 的写法。尽管 JavaScript 能够正确处理,但可能会让其他人感到困惑。
|
||||
**Note**
|
||||
There shouldn't be any spaces between the array name and the square brackets, like `array [0]`. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
|
||||
|
||||
# --instructions--
|
||||
|
||||
创建一个名为 `myData` 的变量,并把 `myArray` 的第一个值赋给它。
|
||||
Create a variable called `myData` and set it to equal the first value of `myArray` using bracket notation.
|
||||
|
||||
# --hints--
|
||||
|
||||
变量 `myData` 的值应为 `myArray` 中的第一个元素值。
|
||||
The variable `myData` should equal the first value of `myArray`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -48,7 +50,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
应使用方括号表示法访问变量 `myArray` 中的元素。
|
||||
The data in variable `myArray` should be accessed using bracket notation.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56592a60ddddeae28f7aa8e1
|
||||
title: 使用索引访问多维数组
|
||||
title: Access Multi-Dimensional Arrays With Indexes
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ckND4Cq'
|
||||
forumTopicId: 16159
|
||||
@ -9,9 +9,9 @@ dashedName: access-multi-dimensional-arrays-with-indexes
|
||||
|
||||
# --description--
|
||||
|
||||
我们可以把<dfn>多维</dfn>数组看作成是*数组中的数组*。使用方括号表示法访问数组时,第一个方括号访问的是数组的第一层,第二个方括号访问的是数组的第二层,以此类推。
|
||||
One way to think of a <dfn>multi-dimensional</dfn> array, is as an *array of arrays*. When you use brackets to access your array, the first set of brackets refers to the entries in the outer-most (the first level) array, and each additional pair of brackets refers to the next level of entries inside.
|
||||
|
||||
**示例**
|
||||
**Example**
|
||||
|
||||
```js
|
||||
var arr = [
|
||||
@ -20,33 +20,30 @@ var arr = [
|
||||
[7,8,9],
|
||||
[[10,11,12], 13, 14]
|
||||
];
|
||||
arr[3]; // 返回 [[10,11,12], 13, 14]
|
||||
arr[3][0]; // 返回 [10,11,12]
|
||||
arr[3][0][1]; // 返回 11
|
||||
arr[3]; // equals [[10,11,12], 13, 14]
|
||||
arr[3][0]; // equals [10,11,12]
|
||||
arr[3][0][1]; // equals 11
|
||||
```
|
||||
|
||||
**注意**
|
||||
数组名与方括号之间不应有空格,不推荐像是 `array [0][0]` 或 `array [0] [0]` 的写法。尽管 JavaScript 能够正确处理,但可能会让其他人感到困惑。
|
||||
**Note**
|
||||
There shouldn't be any spaces between the array name and the square brackets, like `array [0][0]` and even this `array [0] [0]` is not allowed. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用方括号表示法从 `myArray` 中读取元素,使得 `myData` 的值为 `8`。
|
||||
Using bracket notation select an element from `myArray` such that `myData` is equal to `8`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myData` 的值应为 `8`。
|
||||
`myData` should be equal to `8`.
|
||||
|
||||
```js
|
||||
assert(myData === 8);
|
||||
```
|
||||
|
||||
应使用方括号表示法从 `myArray` 中取值。
|
||||
You should be using bracket notation to read the correct value from `myArray`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/myArray\[2\]\[1\]/g.test(code) &&
|
||||
!/myData\s*=\s*(?:.*[-+*/%]|\d)/g.test(code)
|
||||
);
|
||||
assert(/myData=myArray\[2\]\[1\]/.test(__helpers.removeWhiteSpace(code)));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cd
|
||||
title: 访问嵌套数组
|
||||
title: Accessing Nested Arrays
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cLeGDtZ'
|
||||
forumTopicId: 16160
|
||||
@ -9,9 +9,9 @@ dashedName: accessing-nested-arrays
|
||||
|
||||
# --description--
|
||||
|
||||
在之前的挑战中,我们学习了在对象中嵌套对象和数组。与访问嵌套的对象一样,我们可以用方括号表示法来访问嵌套数组。
|
||||
As we have seen in earlier examples, objects can contain both nested objects and nested arrays. Similar to accessing nested objects, Array bracket notation can be chained to access nested arrays.
|
||||
|
||||
下面是访问嵌套数组的例子:
|
||||
Here is an example of how to access a nested array:
|
||||
|
||||
```js
|
||||
var ourPets = [
|
||||
@ -38,17 +38,17 @@ ourPets[1].names[0]; // "Spot"
|
||||
|
||||
# --instructions--
|
||||
|
||||
请使用点号表示法和方括号表示法来检索变量 `myPlants` 中的第二棵树,即返回 `type` 为 `trees` 的数组中的第二个元素。
|
||||
Retrieve the second tree from the variable `myPlants` using object dot and array bracket notation.
|
||||
|
||||
# --hints--
|
||||
|
||||
`secondTree` 的值应为 "pine"。
|
||||
`secondTree` should equal "pine".
|
||||
|
||||
```js
|
||||
assert(secondTree === 'pine');
|
||||
```
|
||||
|
||||
应使用点号表示法和方括号表示法来检索变量 `myPlants`。
|
||||
Your code should use dot and bracket notation to access `myPlants`.
|
||||
|
||||
```js
|
||||
assert(/=\s*myPlants\[1\].list\[1\]/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cc
|
||||
title: 访问嵌套对象
|
||||
title: Accessing Nested Objects
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRnRnfa'
|
||||
forumTopicId: 16161
|
||||
@ -9,9 +9,9 @@ dashedName: accessing-nested-objects
|
||||
|
||||
# --description--
|
||||
|
||||
我们可以通过连续使用点号表示法和方括号表示法来访问对象的嵌套属性。
|
||||
The sub-properties of objects can be accessed by chaining together the dot or bracket notation.
|
||||
|
||||
这是一个访问嵌套对象的示例:
|
||||
Here is a nested object:
|
||||
|
||||
```js
|
||||
var ourStorage = {
|
||||
@ -32,17 +32,17 @@ ourStorage.desk.drawer; // "stapler"
|
||||
|
||||
# --instructions--
|
||||
|
||||
请把 `myStorage` 对象中 `glove box` 的属性值赋给变量 `gloveBoxContents`。请优先使用点号表示法来访问属性;对于点号表示法不能处理的情况,再考虑使用方括号表示法。
|
||||
Access the `myStorage` object and assign the contents of the `glove box` property to the `gloveBoxContents` variable. Use dot notation for all properties where possible, otherwise use bracket notation.
|
||||
|
||||
# --hints--
|
||||
|
||||
`gloveBoxContents` 的值应为 "maps"。
|
||||
`gloveBoxContents` should equal "maps".
|
||||
|
||||
```js
|
||||
assert(gloveBoxContents === 'maps');
|
||||
```
|
||||
|
||||
应使用点号表示法和方括号表示法来访问 `myStorage`。
|
||||
Your code should use dot and bracket notation to access `myStorage`.
|
||||
|
||||
```js
|
||||
assert(/=\s*myStorage\.car\.inside\[\s*("|')glove box\1\s*\]/g.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c8
|
||||
title: 通过方括号表示法访问对象属性
|
||||
title: Accessing Object Properties with Bracket Notation
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBvmEHP'
|
||||
forumTopicId: 16163
|
||||
@ -9,11 +9,11 @@ dashedName: accessing-object-properties-with-bracket-notation
|
||||
|
||||
# --description--
|
||||
|
||||
访问对象的第二种方式是方括号表示法(`[]`)。如果你想访问的属性名中包含空格,就必须使用方括号表示法来获取它的属性值。
|
||||
The second way to access the properties of an object is bracket notation (`[]`). If the property of the object you are trying to access has a space in its name, you will need to use bracket notation.
|
||||
|
||||
当然,如果属性名不包含空格,我们也可以使用方括号表示法。
|
||||
However, you can still use bracket notation on object properties without spaces.
|
||||
|
||||
这是一个使用方括号表示法(`[]`)读取对象属性的例子:
|
||||
Here is a sample of using bracket notation to read an object's property:
|
||||
|
||||
```js
|
||||
var myObj = {
|
||||
@ -26,39 +26,39 @@ myObj['More Space']; // Spock
|
||||
myObj["NoSpace"]; // USS Enterprise
|
||||
```
|
||||
|
||||
注意,属性名中如果包含空格,就必须把属性名称用单引号或双引号包裹起来。
|
||||
Note that property names with spaces in them must be in quotes (single or double).
|
||||
|
||||
# --instructions--
|
||||
|
||||
请使用方括号表示法读取对象 `testObj` 中 `an entree` 和 `the drink` 的属性值,并分别赋值给 `entreeValue` 和 `drinkValue`。
|
||||
Read the values of the properties `"an entree"` and `"the drink"` of `testObj` using bracket notation and assign them to `entreeValue` and `drinkValue` respectively.
|
||||
|
||||
# --hints--
|
||||
|
||||
`entreeValue` 应为一个字符串。
|
||||
`entreeValue` should be a string
|
||||
|
||||
```js
|
||||
assert(typeof entreeValue === 'string');
|
||||
```
|
||||
|
||||
`entreeValue` 的值应为 `"hamburger"`。
|
||||
The value of `entreeValue` should be `"hamburger"`
|
||||
|
||||
```js
|
||||
assert(entreeValue === 'hamburger');
|
||||
```
|
||||
|
||||
`drinkValue` 应为一个字符串。
|
||||
`drinkValue` should be a string
|
||||
|
||||
```js
|
||||
assert(typeof drinkValue === 'string');
|
||||
```
|
||||
|
||||
`drinkValue` 的值应为 `"water"`。
|
||||
The value of `drinkValue` should be `"water"`
|
||||
|
||||
```js
|
||||
assert(drinkValue === 'water');
|
||||
```
|
||||
|
||||
你应使用两次方括号表示法。
|
||||
You should use bracket notation twice
|
||||
|
||||
```js
|
||||
assert(code.match(/testObj\s*?\[('|")[^'"]+\1\]/g).length > 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c7
|
||||
title: 通过点号表示法访问对象属性
|
||||
title: Accessing Object Properties with Dot Notation
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cGryJs8'
|
||||
forumTopicId: 16164
|
||||
@ -9,11 +9,11 @@ dashedName: accessing-object-properties-with-dot-notation
|
||||
|
||||
# --description--
|
||||
|
||||
访问对象属性有两种方式:点号表示法(`.`)和方括号表示法(`[]`)。
|
||||
There are two ways to access the properties of an object: dot notation (`.`) and bracket notation (`[]`), similar to an array.
|
||||
|
||||
如果我们已经提前知道要访问的属性名,使用点号表示法是最方便的。
|
||||
Dot notation is what you use when you know the name of the property you're trying to access ahead of time.
|
||||
|
||||
以下是使用点号表示法读取对象属性的例子:
|
||||
Here is a sample of using dot notation (`.`) to read an object's property:
|
||||
|
||||
```js
|
||||
var myObj = {
|
||||
@ -26,35 +26,35 @@ var prop2val = myObj.prop2; // val2
|
||||
|
||||
# --instructions--
|
||||
|
||||
请使用点号表示法读取对象 `testObj`,把 `hat` 的属性值赋给变量 `hatValue`,把 `shirt` 的属性值赋给 `shirtValue`。
|
||||
Read in the property values of `testObj` using dot notation. Set the variable `hatValue` equal to the object's property `hat` and set the variable `shirtValue` equal to the object's property `shirt`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`hatValue` 应为一个字符串。
|
||||
`hatValue` should be a string
|
||||
|
||||
```js
|
||||
assert(typeof hatValue === 'string');
|
||||
```
|
||||
|
||||
`hatValue` 的值应为 `"ballcap"`。
|
||||
The value of `hatValue` should be `"ballcap"`
|
||||
|
||||
```js
|
||||
assert(hatValue === 'ballcap');
|
||||
```
|
||||
|
||||
`shirtValue` 应为一个字符串。
|
||||
`shirtValue` should be a string
|
||||
|
||||
```js
|
||||
assert(typeof shirtValue === 'string');
|
||||
```
|
||||
|
||||
`shirtValue` 的值应为 `"jersey"`。
|
||||
The value of `shirtValue` should be `"jersey"`
|
||||
|
||||
```js
|
||||
assert(shirtValue === 'jersey');
|
||||
```
|
||||
|
||||
你应使用两次点号表示法。
|
||||
You should use dot notation twice
|
||||
|
||||
```js
|
||||
assert(code.match(/testObj\.\w+/g).length > 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c9
|
||||
title: 通过变量访问对象属性
|
||||
title: Accessing Object Properties with Variables
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cnQyKur'
|
||||
forumTopicId: 16165
|
||||
@ -9,9 +9,9 @@ dashedName: accessing-object-properties-with-variables
|
||||
|
||||
# --description--
|
||||
|
||||
方括号表示法的另一个用途就是访问一个存储在变量中的值所对应的属性值。当你需要遍历对象的所有属性,或者根据一个变量的值查找对应的属性值时,这种写法尤其适用。
|
||||
Another use of bracket notation on objects is to access a property which is stored as the value of a variable. This can be very useful for iterating through an object's properties or when accessing a lookup table.
|
||||
|
||||
以下是一个使用变量来访问属性的例子:
|
||||
Here is an example of using a variable to access a property:
|
||||
|
||||
```js
|
||||
var dogs = {
|
||||
@ -22,7 +22,7 @@ var myBreed = dogs[myDog];
|
||||
console.log(myBreed); // "Doberman"
|
||||
```
|
||||
|
||||
使用此写法的另一种场景是程序执行期间所动态获取的属性名称,如下所示:
|
||||
Another way you can use this concept is when the property's name is collected dynamically during the program execution, as follows:
|
||||
|
||||
```js
|
||||
var someObj = {
|
||||
@ -32,49 +32,49 @@ function propPrefix(str) {
|
||||
var s = "prop";
|
||||
return s + str;
|
||||
}
|
||||
var someProp = propPrefix("Name"); // someProp 的值现在是 'propName'
|
||||
var someProp = propPrefix("Name"); // someProp now holds the value 'propName'
|
||||
console.log(someObj[someProp]); // "John"
|
||||
```
|
||||
|
||||
注意,当我们通过变量名访问属性时,不需要给变量名包裹引号。因为我们实际需要获取的是变量的值,而不是变量的名称。
|
||||
Note that we do *not* use quotes around the variable name when using it to access the property because we are using the *value* of the variable, not the *name*.
|
||||
|
||||
# --instructions--
|
||||
|
||||
首先,请将 `playerNumber` 的值设置为 `16`。然后通过 `playerNumber` 变量,使用方括号表示法获取 `testObj` 中 `16` 的属性值,然后把这个属性值赋给变量 `player`。
|
||||
Set the `playerNumber` variable to `16`. Then, use the variable to look up the player's name and assign it to `player`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`playerNumber` 应为一个数字。
|
||||
`playerNumber` should be a number
|
||||
|
||||
```js
|
||||
assert(typeof playerNumber === 'number');
|
||||
```
|
||||
|
||||
`player` 应为一个字符串。
|
||||
The variable `player` should be a string
|
||||
|
||||
```js
|
||||
assert(typeof player === 'string');
|
||||
```
|
||||
|
||||
`player` 的值应为 "Montana"。
|
||||
The value of `player` should be "Montana"
|
||||
|
||||
```js
|
||||
assert(player === 'Montana');
|
||||
```
|
||||
|
||||
应使用方括号表示法访问 `testObj`。
|
||||
You should use bracket notation to access `testObj`
|
||||
|
||||
```js
|
||||
assert(/testObj\s*?\[.*?\]/.test(code));
|
||||
```
|
||||
|
||||
不应直接将 `Montana` 赋值给 `player`。
|
||||
You should not assign the value `Montana` to the variable `player` directly.
|
||||
|
||||
```js
|
||||
assert(!code.match(/player\s*=\s*"|\'\s*Montana\s*"|\'\s*;/gi));
|
||||
```
|
||||
|
||||
应在中括号里使用 `playerNumber` 变量。
|
||||
You should be using the variable `playerNumber` in your bracket notation
|
||||
|
||||
```js
|
||||
assert(/testObj\s*?\[\s*playerNumber\s*\]/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d2
|
||||
title: 给对象添加新属性
|
||||
title: Add New Properties to a JavaScript Object
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cQe38UD'
|
||||
forumTopicId: 301169
|
||||
@ -9,19 +9,19 @@ dashedName: add-new-properties-to-a-javascript-object
|
||||
|
||||
# --description--
|
||||
|
||||
你也可以像更改属性一样给对象添加属性。
|
||||
You can add new properties to existing JavaScript objects the same way you would modify them.
|
||||
|
||||
我们可以像这样给 `ourDog` 添加 `"bark"` 属性:
|
||||
Here's how we would add a `"bark"` property to `ourDog`:
|
||||
|
||||
`ourDog.bark = "bow-wow";`
|
||||
|
||||
或者
|
||||
or
|
||||
|
||||
`ourDog["bark"] = "bow-wow";`
|
||||
|
||||
现在当我们访问 `ourDog.bark` 时会得到它 bark 的属性值 "bow-wow".
|
||||
Now when we evaluate `ourDog.bark`, we'll get his bark, "bow-wow".
|
||||
|
||||
代码示例:
|
||||
Example:
|
||||
|
||||
```js
|
||||
var ourDog = {
|
||||
@ -36,17 +36,17 @@ ourDog.bark = "bow-wow";
|
||||
|
||||
# --instructions--
|
||||
|
||||
请给 `myDog` 添加一个 `"bark"` 属性,将它的值设置为狗的叫声,如 "woof"。你可以使用点号表示法或方括号表示法来完成此挑战。
|
||||
Add a `"bark"` property to `myDog` and set it to a dog sound, such as "woof". You may use either dot or bracket notation.
|
||||
|
||||
# --hints--
|
||||
|
||||
应给 `myDog` 添加 `"bark"` 属性。
|
||||
You should add the property `"bark"` to `myDog`.
|
||||
|
||||
```js
|
||||
assert(myDog.bark !== undefined);
|
||||
```
|
||||
|
||||
不应在初始化 myDog 的时候添加 `"bark"` 属性。
|
||||
You should not add `"bark"` to the setup section.
|
||||
|
||||
```js
|
||||
assert(!/bark[^\n]:/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb3bdef
|
||||
title: 加法运算
|
||||
title: Add Two Numbers with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cM2KBAG'
|
||||
forumTopicId: 16650
|
||||
@ -9,31 +9,31 @@ dashedName: add-two-numbers-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
`Number` 是 JavaScript 中的一种数据类型,用来表示数值。
|
||||
`Number` is a data type in JavaScript which represents numeric data.
|
||||
|
||||
现在我们来尝试在 JavaScript 中做加法运算。
|
||||
Now let's try to add two numbers using JavaScript.
|
||||
|
||||
JavaScript 中,我们通过符号 `+` 来进行加法运算。
|
||||
JavaScript uses the `+` symbol as an addition operator when placed between two numbers.
|
||||
|
||||
**示例:**
|
||||
**Example:**
|
||||
|
||||
```js
|
||||
myVar = 5 + 10; // 赋值 15
|
||||
myVar = 5 + 10; // assigned 15
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
请改变数字 `0` 让变量 sum 的值为 `20`。
|
||||
Change the `0` so that sum will equal `20`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sum` 的值应为 `20`。
|
||||
`sum` should equal `20`.
|
||||
|
||||
```js
|
||||
assert(sum === 20);
|
||||
```
|
||||
|
||||
应使用 `+` 运算符。
|
||||
You should use the `+` operator.
|
||||
|
||||
```js
|
||||
assert(/\+/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244de
|
||||
title: 在 Switch 语句中添加默认选项
|
||||
title: Adding a Default Option in Switch Statements
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c3JvVfg'
|
||||
forumTopicId: 16653
|
||||
@ -9,9 +9,9 @@ dashedName: adding-a-default-option-in-switch-statements
|
||||
|
||||
# --description--
|
||||
|
||||
在 `switch` 语句中你可能无法用 case 来指明所有情况,这时我们可以添加 default 语句来解决这个问题。在无法找到匹配的 case 时,default 语句就会执行。这非常类似于 if/else 语句中的 else 语句。
|
||||
In a `switch` statement you may not be able to specify all possible values as `case` statements. Instead, you can add the `default` statement which will be executed if no matching `case` statements are found. Think of it like the final `else` statement in an `if/else` chain.
|
||||
|
||||
注意,`default` 语句应该在所有的 `case` 之后。
|
||||
A `default` statement should be the last case.
|
||||
|
||||
```js
|
||||
switch (num) {
|
||||
@ -30,7 +30,7 @@ switch (num) {
|
||||
|
||||
# --instructions--
|
||||
|
||||
请实现根据下面的条件来设置 `answer` 的 `switch` 语句:
|
||||
Write a switch statement to set `answer` for the following conditions:
|
||||
`"a"` - "apple"
|
||||
`"b"` - "bird"
|
||||
`"c"` - "cat"
|
||||
@ -38,49 +38,49 @@ switch (num) {
|
||||
|
||||
# --hints--
|
||||
|
||||
`switchOfStuff("a")` 的值应为 "apple"。
|
||||
`switchOfStuff("a")` should have a value of "apple"
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('a') === 'apple');
|
||||
```
|
||||
|
||||
`switchOfStuff("b")` 的值应为 "bird"。
|
||||
`switchOfStuff("b")` should have a value of "bird"
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('b') === 'bird');
|
||||
```
|
||||
|
||||
`switchOfStuff("c")` 的值应为 "cat"。
|
||||
`switchOfStuff("c")` should have a value of "cat"
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('c') === 'cat');
|
||||
```
|
||||
|
||||
`switchOfStuff("d")` 的值应为 "stuff"。
|
||||
`switchOfStuff("d")` should have a value of "stuff"
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('d') === 'stuff');
|
||||
```
|
||||
|
||||
`switchOfStuff("4")` 的值应为 "stuff"。
|
||||
`switchOfStuff(4)` should have a value of "stuff"
|
||||
|
||||
```js
|
||||
assert(switchOfStuff(4) === 'stuff');
|
||||
```
|
||||
|
||||
不应使用 `if` 或 `else` 语句。
|
||||
You should not use any `if` or `else` statements
|
||||
|
||||
```js
|
||||
assert(!/else/g.test(code) || !/if/g.test(code));
|
||||
```
|
||||
|
||||
应有一个 `default` 语句。
|
||||
You should use a `default` statement
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('string-to-trigger-default-case') === 'stuff');
|
||||
```
|
||||
|
||||
应至少有 3 个 `break` 语句。
|
||||
You should have at least 3 `break` statements
|
||||
|
||||
```js
|
||||
assert(code.match(/break/g).length > 2);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ed
|
||||
title: 将变量追加到字符串
|
||||
title: Appending Variables to Strings
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cbQmZfa'
|
||||
forumTopicId: 16656
|
||||
@ -9,30 +9,30 @@ dashedName: appending-variables-to-strings
|
||||
|
||||
# --description--
|
||||
|
||||
我们不仅可以通过字符串的<dfn>字面量</dfn>创建多行字符串,还可以使用加法赋值运算符(`+=`)来将变量追加到字符串。
|
||||
Just as we can build a string over multiple lines out of string <dfn>literals</dfn>, we can also append variables to a string using the plus equals (`+=`) operator.
|
||||
|
||||
代码示例:
|
||||
Example:
|
||||
|
||||
```js
|
||||
var anAdjective = "awesome!";
|
||||
var ourStr = "freeCodeCamp is ";
|
||||
ourStr += anAdjective;
|
||||
// ourStr 的值现在为 "freeCodeCamp is awesome!"
|
||||
// ourStr is now "freeCodeCamp is awesome!"
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
请将变量 `someAdjective` 的设置为包含至少三个字符的字符串,并使用 `+=` 运算符把它追加到变量 `myStr` 上。
|
||||
Set `someAdjective` to a string of at least 3 characters and append it to `myStr` using the `+=` operator.
|
||||
|
||||
# --hints--
|
||||
|
||||
`someAdjective` 应为至少包含三个字符的字符串。
|
||||
`someAdjective` should be set to a string at least 3 characters long.
|
||||
|
||||
```js
|
||||
assert(typeof someAdjective !== 'undefined' && someAdjective.length > 2);
|
||||
```
|
||||
|
||||
应使用 `+=` 操作符把 `someAdjective` 追加到 `myStr` 的末尾。
|
||||
You should append `someAdjective` to `myStr` using the `+=` operator.
|
||||
|
||||
```js
|
||||
assert(code.match(/myStr\s*\+=\s*someAdjective\s*/).length > 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5ee127a03c3b35dd45426493
|
||||
title: 将变量的值赋给另一个变量
|
||||
title: Assigning the Value of One Variable to Another
|
||||
challengeType: 1
|
||||
videoUrl: ''
|
||||
forumTopicId: 418265
|
||||
@ -9,7 +9,7 @@ dashedName: assigning-the-value-of-one-variable-to-another
|
||||
|
||||
# --description--
|
||||
|
||||
使用<dfn>赋值</dfn>运算符将值赋给变量后,我们可以继续使用<dfn>赋值</dfn>运算符将这个变量的值赋给其它变量。
|
||||
After a value is assigned to a variable using the <dfn>assignment</dfn> operator, you can assign the value of that variable to another variable using the <dfn>assignment</dfn> operator.
|
||||
|
||||
```js
|
||||
var myVar;
|
||||
@ -18,27 +18,27 @@ var myNum;
|
||||
myNum = myVar;
|
||||
```
|
||||
|
||||
在上面的代码中,我们声明了没有初始值的 `myVar` 变量,然后给它赋值 `5`。接下来,我们又声明了没有初始值的变量 `myNum`。之后,`myVar` 的值 `5` 被赋给了变量 `myNum`。现在,`myNum` 的值也是 `5`。
|
||||
The above declares a `myVar` variable with no value, then assigns it the value `5`. Next, a variable named `myNum` is declared with no value. Then, the contents of `myVar` (which is `5`) is assigned to the variable `myNum`. Now, `myNum` also has the value of `5`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
请把 `a` 的值赋给 `b`。
|
||||
Assign the contents of `a` to variable `b`.
|
||||
|
||||
# --hints--
|
||||
|
||||
不应修改注释上方的代码。
|
||||
You should not change code above the specified comment.
|
||||
|
||||
```js
|
||||
assert(/var a;/.test(code) && /a = 7;/.test(code) && /var b;/.test(code));
|
||||
```
|
||||
|
||||
`b` 的值应为 7。
|
||||
`b` should have a value of 7.
|
||||
|
||||
```js
|
||||
assert(typeof b === 'number' && b === 7);
|
||||
```
|
||||
|
||||
`a` 的值应通过 `=` 运算符赋给 `b`。
|
||||
`a` should be assigned to `b` with `=`.
|
||||
|
||||
```js
|
||||
assert(/b\s*=\s*a\s*/g.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c3
|
||||
title: 用返回值来赋值
|
||||
title: Assignment with a Returned Value
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ce2pEtB'
|
||||
forumTopicId: 16658
|
||||
@ -9,30 +9,30 @@ dashedName: assignment-with-a-returned-value
|
||||
|
||||
# --description--
|
||||
|
||||
在[使用赋值运算符存储值](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator)这一挑战中我们曾提到,赋值发生之前会先完成等号右边的操作。这意味着我们可把一个函数的返回值赋给一个变量。
|
||||
If you'll recall from our discussion of [Storing Values with the Assignment Operator](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator), everything to the right of the equal sign is resolved before the value is assigned. This means we can take the return value of a function and assign it to a variable.
|
||||
|
||||
假设我们已经定义了函数 `sum`,它的作用就是将两个数字相加,那么:
|
||||
Assume we have pre-defined a function `sum` which adds two numbers together, then:
|
||||
|
||||
`ourSum = sum(5, 12);`
|
||||
|
||||
会调用 `sum` 函数,函数返回数值 `17`,然后把它赋值给 `ourSum` 变量。
|
||||
will call `sum` function, which returns a value of `17` and assigns it to `ourSum` variable.
|
||||
|
||||
# --instructions--
|
||||
|
||||
请调用 `processArg` 函数并传入 `7` 作为参数,然后把返回值赋值给变量 `processed`。
|
||||
Call the `processArg` function with an argument of `7` and assign its return value to the variable `processed`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`processed` 的值应为 `2`。
|
||||
`processed` should have a value of `2`
|
||||
|
||||
```js
|
||||
assert(processed === 2);
|
||||
```
|
||||
|
||||
应将 `processArg` 的返回值赋给 `processed`。
|
||||
You should assign `processArg` to `processed`
|
||||
|
||||
```js
|
||||
assert(/processed\s*=\s*processArg\(\s*7\s*\)\s*;/.test(code));
|
||||
assert(/processed\s*=\s*processArg\(\s*7\s*\)/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d0
|
||||
title: 创建 JavaScript 对象
|
||||
title: Build JavaScript Objects
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWGkbtd'
|
||||
forumTopicId: 16769
|
||||
@ -9,13 +9,13 @@ dashedName: build-javascript-objects
|
||||
|
||||
# --description--
|
||||
|
||||
你可能听说过对象(`object`)这个概念。
|
||||
You may have heard the term `object` before.
|
||||
|
||||
对象和数组很相似。区别在于,数组是通过索引来访问和修改数据,而对象是通过`属性`来访问和修改数据。
|
||||
Objects are similar to `arrays`, except that instead of using indexes to access and modify their data, you access the data in objects through what are called `properties`.
|
||||
|
||||
对象可以让存储的数据结构化,它可以让我们更好地描述真实世界的物体,比如一只猫。
|
||||
Objects are useful for storing data in a structured way, and can represent real world objects, like a cat.
|
||||
|
||||
这是一个对象的示例:
|
||||
Here's a sample cat object:
|
||||
|
||||
```js
|
||||
var cat = {
|
||||
@ -26,7 +26,7 @@ var cat = {
|
||||
};
|
||||
```
|
||||
|
||||
在这个示例中,属性都是以字符串的形式储存,例如 `"name"`、`"legs"`、`"tails"`。然而,我们也可以使用数字作为属性,甚至可以省略字符串属性的引号,如下所示:
|
||||
In this example, all the properties are stored as strings, such as - `"name"`, `"legs"`, and `"tails"`. However, you can also use numbers as properties. You can even omit the quotes for single-word string properties, as follows:
|
||||
|
||||
```js
|
||||
var anotherObject = {
|
||||
@ -36,17 +36,17 @@ var anotherObject = {
|
||||
};
|
||||
```
|
||||
|
||||
但是,如果你的对象包含任何非字符串属性,JavaScript 也会将它们自动转换为字符串。
|
||||
However, if your object has any non-string properties, JavaScript will automatically typecast them as strings.
|
||||
|
||||
# --instructions--
|
||||
|
||||
请创建一个名为 `myDog` 的对象,它应包含这些属性:`"name"`、`"legs"`、`"tails"`、`"friends"`。
|
||||
Make an object that represents a dog called `myDog` which contains the properties `"name"` (a string), `"legs"`, `"tails"` and `"friends"`.
|
||||
|
||||
请确保 `"name"` 属性值是字符串、`"legs"` 和 `"tails"` 属性值是数字、`"friends"` 属性值是数组。只要满足这些条件,你可以随意设定这些属性值。
|
||||
You can set these object properties to whatever values you want, as long as `"name"` is a string, `"legs"` and `"tails"` are numbers, and `"friends"` is an array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myDog` 应包含 `name` 属性,且属性值是一个字符串。
|
||||
`myDog` should contain the property `name` and it should be a `string`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -64,7 +64,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` 应包含 `legs` 属性,且属性值是一个数字。
|
||||
`myDog` should contain the property `legs` and it should be a `number`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -82,7 +82,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` 应包含 `tails` 属性,且属性值是一个数字。
|
||||
`myDog` should contain the property `tails` and it should be a `number`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -100,7 +100,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` 应包含 `friends` 属性,且属性值是一个数组。
|
||||
`myDog` should contain the property `friends` and it should be an `array`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -118,7 +118,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` 应只包含给定的属性。
|
||||
`myDog` should only contain all the given properties.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244dc
|
||||
title: 多个 if else 语句
|
||||
title: Chaining If Else Statements
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/caeJgsw'
|
||||
forumTopicId: 16772
|
||||
@ -9,7 +9,7 @@ dashedName: chaining-if-else-statements
|
||||
|
||||
# --description--
|
||||
|
||||
将 `if/else` 语句串联在一起可以实现复杂的逻辑,这是多个 `if/else if` 语句串联在一起的<dfn>伪代码</dfn>:
|
||||
`if/else` statements can be chained together for complex logic. Here is <dfn>pseudocode</dfn> of multiple chained `if` / `else if` statements:
|
||||
|
||||
```js
|
||||
if (condition1) {
|
||||
@ -26,89 +26,89 @@ if (condition1) {
|
||||
|
||||
# --instructions--
|
||||
|
||||
请将 `if`/`else if` 语句串联起来实现下面的逻辑:
|
||||
Write chained `if`/`else if` statements to fulfill the following conditions:
|
||||
|
||||
`num < 5` - 返回 "Tiny"
|
||||
`num < 10` - 返回 "Small"
|
||||
`num < 15` - 返回 "Medium"
|
||||
`num < 20` - 返回 "Large"
|
||||
`num >= 20` - 返回 "Huge"
|
||||
`num < 5` - return "Tiny"
|
||||
`num < 10` - return "Small"
|
||||
`num < 15` - return "Medium"
|
||||
`num < 20` - return "Large"
|
||||
`num >= 20` - return "Huge"
|
||||
|
||||
# --hints--
|
||||
|
||||
应至少有 4 个 `else` 语句。
|
||||
You should have at least four `else` statements
|
||||
|
||||
```js
|
||||
assert(code.match(/else/g).length > 3);
|
||||
```
|
||||
|
||||
应至少有 4 个 `if` 语句。
|
||||
You should have at least four `if` statements
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length > 3);
|
||||
```
|
||||
|
||||
应至少有 1 个 `return` 语句。
|
||||
You should have at least one `return` statement
|
||||
|
||||
```js
|
||||
assert(code.match(/return/g).length >= 1);
|
||||
```
|
||||
|
||||
`testSize(0)` 应返回 "Tiny"。
|
||||
`testSize(0)` should return "Tiny"
|
||||
|
||||
```js
|
||||
assert(testSize(0) === 'Tiny');
|
||||
```
|
||||
|
||||
`testSize(4)` 应返回 "Tiny"。
|
||||
`testSize(4)` should return "Tiny"
|
||||
|
||||
```js
|
||||
assert(testSize(4) === 'Tiny');
|
||||
```
|
||||
|
||||
`testSize(5)` 应返回 "Small"。
|
||||
`testSize(5)` should return "Small"
|
||||
|
||||
```js
|
||||
assert(testSize(5) === 'Small');
|
||||
```
|
||||
|
||||
`testSize(8)` 应返回 "Small"。
|
||||
`testSize(8)` should return "Small"
|
||||
|
||||
```js
|
||||
assert(testSize(8) === 'Small');
|
||||
```
|
||||
|
||||
`testSize(10)` 应返回 "Medium"。
|
||||
`testSize(10)` should return "Medium"
|
||||
|
||||
```js
|
||||
assert(testSize(10) === 'Medium');
|
||||
```
|
||||
|
||||
`testSize(14)` 应返回 "Medium"。
|
||||
`testSize(14)` should return "Medium"
|
||||
|
||||
```js
|
||||
assert(testSize(14) === 'Medium');
|
||||
```
|
||||
|
||||
`testSize(15)` 应返回 "Large"。
|
||||
`testSize(15)` should return "Large"
|
||||
|
||||
```js
|
||||
assert(testSize(15) === 'Large');
|
||||
```
|
||||
|
||||
`testSize(17)` 应返回 "Large"。
|
||||
`testSize(17)` should return "Large"
|
||||
|
||||
```js
|
||||
assert(testSize(17) === 'Large');
|
||||
```
|
||||
|
||||
`testSize(20)` 应返回 "Huge"。
|
||||
`testSize(20)` should return "Huge"
|
||||
|
||||
```js
|
||||
assert(testSize(20) === 'Huge');
|
||||
```
|
||||
|
||||
`testSize(25)` 应返回 "Huge"。
|
||||
`testSize(25)` should return "Huge"
|
||||
|
||||
```js
|
||||
assert(testSize(25) === 'Huge');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7123c9c441eddfaeb4bdef
|
||||
title: 给代码添加注释
|
||||
title: Comment Your JavaScript Code
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c7ynnTp'
|
||||
forumTopicId: 16783
|
||||
@ -9,39 +9,39 @@ dashedName: comment-your-javascript-code
|
||||
|
||||
# --description--
|
||||
|
||||
被注释的代码块在 JavaScript 之中是不会执行的。在代码中写注释是一个非常好的方式让你自己和其他人理解代码。
|
||||
Comments are lines of code that JavaScript will intentionally ignore. Comments are a great way to leave notes to yourself and to other people who will later need to figure out what that code does.
|
||||
|
||||
JavaScript 中的注释方式有以下两种:
|
||||
There are two ways to write comments in JavaScript:
|
||||
|
||||
使用`//`注释掉当前行的代码
|
||||
Using `//` will tell JavaScript to ignore the remainder of the text on the current line:
|
||||
|
||||
```js
|
||||
// This is an in-line comment.
|
||||
```
|
||||
|
||||
你也可以使用多行注释来注释你的代码,以<code>/<em></em></code>*开始,用\`\`*`/`来结束,就像下面这样:
|
||||
You can make a multi-line comment beginning with `/*` and ending with `*/`:
|
||||
|
||||
```js
|
||||
/* This is a
|
||||
multi-line comment */
|
||||
```
|
||||
|
||||
**最佳实践**
|
||||
写代码的时候,要定期添加注释对部分代码块进行解释。适当的注释能让别人和你自己更容易看懂代码。
|
||||
**Best Practice**
|
||||
As you write code, you should regularly add comments to clarify the function of parts of your code. Good commenting can help communicate the intent of your code—both for others *and* for your future self.
|
||||
|
||||
# --instructions--
|
||||
|
||||
尝试创建这两种类型的注释。
|
||||
Try creating one of each type of comment.
|
||||
|
||||
# --hints--
|
||||
|
||||
创建一个`//`样式的注释, 被注释的文本至少要包含 5 个字符。
|
||||
You should create a `//` style comment that contains at least five letters.
|
||||
|
||||
```js
|
||||
assert(code.match(/(\/\/)...../g));
|
||||
```
|
||||
|
||||
创建一个`/* */`样式的注释, 被注释的文本至少要包含 5 个字符。
|
||||
You should create a `/* */` style comment that contains at least five letters.
|
||||
|
||||
```js
|
||||
assert(code.match(/(\/\*)([^\/]{5,})(?=\*\/)/gm));
|
||||
@ -50,7 +50,6 @@ assert(code.match(/(\/\*)([^\/]{5,})(?=\*\/)/gm));
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
```
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d0
|
||||
title: 相等运算符
|
||||
title: Comparison with the Equality Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cKyVMAL'
|
||||
forumTopicId: 16784
|
||||
@ -9,9 +9,9 @@ dashedName: comparison-with-the-equality-operator
|
||||
|
||||
# --description--
|
||||
|
||||
在 JavaScript 中,有很多<dfn>相互比较的操作</dfn>。所有这些操作符都返回一个`true`或`false`值。
|
||||
There are many <dfn>comparison operators</dfn> in JavaScript. All of these operators return a boolean `true` or `false` value.
|
||||
|
||||
最基本的运算符是相等运算符:`==`。相等运算符比较两个值,如果它们是同等,返回`true`,如果它们不等,返回`false`。值得注意的是相等运算符不同于赋值运算符(`=`),赋值运算符是把等号右边的值赋给左边的变量。
|
||||
The most basic operator is the equality operator `==`. The equality operator compares two values and returns `true` if they're equivalent or `false` if they are not. Note that equality is different from assignment (`=`), which assigns the value on the right of the operator to a variable on the left.
|
||||
|
||||
```js
|
||||
function equalityTest(myVal) {
|
||||
@ -22,7 +22,7 @@ function equalityTest(myVal) {
|
||||
}
|
||||
```
|
||||
|
||||
如果`myVal`等于`10`,相等运算符会返回`true`,因此大括号里面的代码会被执行,函数将返回`"Equal"`。否则,函数返回`"Not Equal"`。 在 JavaScript 中,为了让两个不同的`数据类型`(例如`数字`和`字符串`)的值可以作比较,它必须把一种类型转换为另一种类型。然而一旦这样做,它可以像下面这样来比较:
|
||||
If `myVal` is equal to `10`, the equality operator returns `true`, so the code in the curly braces will execute, and the function will return `"Equal"`. Otherwise, the function will return `"Not Equal"`. In order for JavaScript to compare two different <dfn>data types</dfn> (for example, `numbers` and `strings`), it must convert one type to another. This is known as "Type Coercion". Once it does, however, it can compare terms as follows:
|
||||
|
||||
```js
|
||||
1 == 1 // true
|
||||
@ -33,29 +33,29 @@ function equalityTest(myVal) {
|
||||
|
||||
# --instructions--
|
||||
|
||||
把`相等运算符`添加到指定的行,这样当`val`的值为`12`的时候,函数会返回"Equal"。
|
||||
Add the equality operator to the indicated line so that the function will return "Equal" when `val` is equivalent to `12`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testEqual(10)`应该返回 "Not Equal"。
|
||||
`testEqual(10)` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testEqual(10) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testEqual(12)`应该返回 "Equal"。
|
||||
`testEqual(12)` should return "Equal"
|
||||
|
||||
```js
|
||||
assert(testEqual(12) === 'Equal');
|
||||
```
|
||||
|
||||
`testEqual("12")`应该返回 "Equal"。
|
||||
`testEqual("12")` should return "Equal"
|
||||
|
||||
```js
|
||||
assert(testEqual('12') === 'Equal');
|
||||
```
|
||||
|
||||
你应该使用`==`运算符。
|
||||
You should use the `==` operator
|
||||
|
||||
```js
|
||||
assert(code.match(/==/g) && !code.match(/===/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d4
|
||||
title: 大于运算符
|
||||
title: Comparison with the Greater Than Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cp6GbH4'
|
||||
forumTopicId: 16786
|
||||
@ -9,11 +9,11 @@ dashedName: comparison-with-the-greater-than-operator
|
||||
|
||||
# --description--
|
||||
|
||||
使用大于运算符(`>`)来比较两个数字。如果大于运算符左边的数字大于右边的数字,将会返回`true`。否则,它返回`false`。
|
||||
The greater than operator (`>`) compares the values of two numbers. If the number to the left is greater than the number to the right, it returns `true`. Otherwise, it returns `false`.
|
||||
|
||||
与相等运算符一样,大于运算符在比较的时候,会转换值的数据类型。
|
||||
Like the equality operator, greater than operator will convert data types of values while comparing.
|
||||
|
||||
**例如**
|
||||
**Examples**
|
||||
|
||||
```js
|
||||
5 > 3 // true
|
||||
@ -24,53 +24,53 @@ dashedName: comparison-with-the-greater-than-operator
|
||||
|
||||
# --instructions--
|
||||
|
||||
添加`大于`运算符到指定的行,使得返回的语句是有意义的。
|
||||
Add the greater than operator to the indicated lines so that the return statements make sense.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testGreaterThan(0)`应该返回 "10 or Under"。
|
||||
`testGreaterThan(0)` should return "10 or Under"
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(0) === '10 or Under');
|
||||
```
|
||||
|
||||
`testGreaterThan(10)`应该返回 "10 or Under"。
|
||||
`testGreaterThan(10)` should return "10 or Under"
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(10) === '10 or Under');
|
||||
```
|
||||
|
||||
`testGreaterThan(11)`应该返回 "Over 10"。
|
||||
`testGreaterThan(11)` should return "Over 10"
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(11) === 'Over 10');
|
||||
```
|
||||
|
||||
`testGreaterThan(99)`应该返回 "Over 10"。
|
||||
`testGreaterThan(99)` should return "Over 10"
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(99) === 'Over 10');
|
||||
```
|
||||
|
||||
`testGreaterThan(100)`应该返回 "Over 10"。
|
||||
`testGreaterThan(100)` should return "Over 10"
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(100) === 'Over 10');
|
||||
```
|
||||
|
||||
`testGreaterThan(101)`应该返回 "Over 100"。
|
||||
`testGreaterThan(101)` should return "Over 100"
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(101) === 'Over 100');
|
||||
```
|
||||
|
||||
`testGreaterThan(150)`应该返回 "Over 100"。
|
||||
`testGreaterThan(150)` should return "Over 100"
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(150) === 'Over 100');
|
||||
```
|
||||
|
||||
你应该使用`>`运算符至少两次。
|
||||
You should use the `>` operator at least twice
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*>\s*('|")*\d+('|")*/g).length > 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d5
|
||||
title: 大于或等于运算符
|
||||
title: Comparison with the Greater Than Or Equal To Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c6KBqtV'
|
||||
forumTopicId: 16785
|
||||
@ -9,11 +9,11 @@ dashedName: comparison-with-the-greater-than-or-equal-to-operator
|
||||
|
||||
# --description--
|
||||
|
||||
使用`大于等于`运算符(`>=`)来比较两个数字的大小。如果大于等于运算符左边的数字比右边的数字大或者相等,它会返回`true`。否则,它会返回`false`。
|
||||
The greater than or equal to operator (`>=`) compares the values of two numbers. If the number to the left is greater than or equal to the number to the right, it returns `true`. Otherwise, it returns `false`.
|
||||
|
||||
与相等运算符相似,`大于等于`运算符在比较的时候会转换值的数据类型。
|
||||
Like the equality operator, `greater than or equal to` operator will convert data types while comparing.
|
||||
|
||||
**例如**
|
||||
**Examples**
|
||||
|
||||
```js
|
||||
6 >= 6 // true
|
||||
@ -24,53 +24,53 @@ dashedName: comparison-with-the-greater-than-or-equal-to-operator
|
||||
|
||||
# --instructions--
|
||||
|
||||
添加`大于等于`运算符到指定行,使得函数的返回语句有意义。
|
||||
Add the greater than or equal to operator to the indicated lines so that the return statements make sense.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testGreaterOrEqual(0)`应该返回 "Less than 10"。
|
||||
`testGreaterOrEqual(0)` should return "Less than 10"
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(0) === 'Less than 10');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(9)`应该返回 "Less than 10"。
|
||||
`testGreaterOrEqual(9)` should return "Less than 10"
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(9) === 'Less than 10');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(10)`应该返回 "10 or Over"。
|
||||
`testGreaterOrEqual(10)` should return "10 or Over"
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(10) === '10 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(11)`应该返回 "10 or Over"。
|
||||
`testGreaterOrEqual(11)` should return "10 or Over"
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(11) === '10 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(19)`应该返回 "10 or Over"。
|
||||
`testGreaterOrEqual(19)` should return "10 or Over"
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(19) === '10 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(100)`应该返回 "20 or Over"。
|
||||
`testGreaterOrEqual(100)` should return "20 or Over"
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(100) === '20 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(21)`应该返回 "20 or Over"。
|
||||
`testGreaterOrEqual(21)` should return "20 or Over"
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(21) === '20 or Over');
|
||||
```
|
||||
|
||||
你应该使用`>=`运算符至少两次。
|
||||
You should use the `>=` operator at least twice
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*>=\s*('|")*\d+('|")*/g).length > 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d2
|
||||
title: 不等运算符
|
||||
title: Comparison with the Inequality Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cdBm9Sr'
|
||||
forumTopicId: 16787
|
||||
@ -9,9 +9,9 @@ dashedName: comparison-with-the-inequality-operator
|
||||
|
||||
# --description--
|
||||
|
||||
不相等运算符(`!=`)与相等运算符是相反的。这意味着不相等运算符中,如果“不为真”并且返回`false`的地方,在相等运算符中会返回`true`,*反之亦然*。与相等运算符类似,不相等运算符在比较的时候也会转换值的数据类型。
|
||||
The inequality operator (`!=`) is the opposite of the equality operator. It means "Not Equal" and returns `false` where equality would return `true` and *vice versa*. Like the equality operator, the inequality operator will convert data types of values while comparing.
|
||||
|
||||
**例如**
|
||||
**Examples**
|
||||
|
||||
```js
|
||||
1 != 2 // true
|
||||
@ -23,41 +23,41 @@ dashedName: comparison-with-the-inequality-operator
|
||||
|
||||
# --instructions--
|
||||
|
||||
在`if`语句中,添加不相等运算符`!=`,这样函数在当`val`不等于 `99`的时候,会返回 "Not Equal"。
|
||||
Add the inequality operator `!=` in the `if` statement so that the function will return "Not Equal" when `val` is not equivalent to `99`
|
||||
|
||||
# --hints--
|
||||
|
||||
`testNotEqual(99)`应该返回 "Equal"。
|
||||
`testNotEqual(99)` should return "Equal"
|
||||
|
||||
```js
|
||||
assert(testNotEqual(99) === 'Equal');
|
||||
```
|
||||
|
||||
`testNotEqual("99")`应该返回 "Equal"。
|
||||
`testNotEqual("99")` should return "Equal"
|
||||
|
||||
```js
|
||||
assert(testNotEqual('99') === 'Equal');
|
||||
```
|
||||
|
||||
`testNotEqual(12)`应该返回 "Not Equal"。
|
||||
`testNotEqual(12)` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testNotEqual(12) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testNotEqual("12")`应该返回 "Not Equal"。
|
||||
`testNotEqual("12")` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testNotEqual('12') === 'Not Equal');
|
||||
```
|
||||
|
||||
`testNotEqual("bob")`应该返回 "Not Equal"。
|
||||
`testNotEqual("bob")` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testNotEqual('bob') === 'Not Equal');
|
||||
```
|
||||
|
||||
你应该使用`!=`运算符。
|
||||
You should use the `!=` operator
|
||||
|
||||
```js
|
||||
assert(code.match(/(?!!==)!=/));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d6
|
||||
title: 小于运算符
|
||||
title: Comparison with the Less Than Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNVRWtB'
|
||||
forumTopicId: 16789
|
||||
@ -9,9 +9,9 @@ dashedName: comparison-with-the-less-than-operator
|
||||
|
||||
# --description--
|
||||
|
||||
使用<dfn>小于</dfn>运算符(`<`)比较两个数字的大小。如果小于运算符左边的数字比右边的数字小,它会返回`true`。否则会返回`false`。与相等运算符类似,<dfn>小于</dfn> 运算符在做比较的时候会转换值的数据类型。
|
||||
The <dfn>less than</dfn> operator (`<`) compares the values of two numbers. If the number to the left is less than the number to the right, it returns `true`. Otherwise, it returns `false`. Like the equality operator, <dfn>less than</dfn> operator converts data types while comparing.
|
||||
|
||||
**例如**
|
||||
**Examples**
|
||||
|
||||
```js
|
||||
2 < 5 // true
|
||||
@ -23,47 +23,47 @@ dashedName: comparison-with-the-less-than-operator
|
||||
|
||||
# --instructions--
|
||||
|
||||
添加`小于`运算符到指定行,使得函数的返回语句有意义。
|
||||
Add the less than operator to the indicated lines so that the return statements make sense.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testLessThan(0)`应该返回 "Under 25"。
|
||||
`testLessThan(0)` should return "Under 25"
|
||||
|
||||
```js
|
||||
assert(testLessThan(0) === 'Under 25');
|
||||
```
|
||||
|
||||
`testLessThan(24)`应该返回 "Under 25"。
|
||||
`testLessThan(24)` should return "Under 25"
|
||||
|
||||
```js
|
||||
assert(testLessThan(24) === 'Under 25');
|
||||
```
|
||||
|
||||
`testLessThan(25)`应该返回 "Under 55"。
|
||||
`testLessThan(25)` should return "Under 55"
|
||||
|
||||
```js
|
||||
assert(testLessThan(25) === 'Under 55');
|
||||
```
|
||||
|
||||
`testLessThan(54)`应该返回 "Under 55"。
|
||||
`testLessThan(54)` should return "Under 55"
|
||||
|
||||
```js
|
||||
assert(testLessThan(54) === 'Under 55');
|
||||
```
|
||||
|
||||
`testLessThan(55)`应该返回 "55 or Over"。
|
||||
`testLessThan(55)` should return "55 or Over"
|
||||
|
||||
```js
|
||||
assert(testLessThan(55) === '55 or Over');
|
||||
```
|
||||
|
||||
`testLessThan(99)`应该返回 "55 or Over"。
|
||||
`testLessThan(99)` should return "55 or Over"
|
||||
|
||||
```js
|
||||
assert(testLessThan(99) === '55 or Over');
|
||||
```
|
||||
|
||||
你应该使用`<`运算符至少两次。
|
||||
You should use the `<` operator at least twice
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*<\s*('|")*\d+('|")*/g).length > 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d7
|
||||
title: 小于或等于运算符
|
||||
title: Comparison with the Less Than Or Equal To Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNVR7Am'
|
||||
forumTopicId: 16788
|
||||
@ -9,9 +9,9 @@ dashedName: comparison-with-the-less-than-or-equal-to-operator
|
||||
|
||||
# --description--
|
||||
|
||||
使用`小于等于`运算符(`<=`)比较两个数字的大小。如果在小于等于运算符左边的数字小于或者等于右边的数字,它会返回`true`。如果在小于等于运算符左边的数字大于右边的数字,它会返回`false`。与相等运算符类似,`小于等于`运算符会转换数据类型。
|
||||
The less than or equal to operator (`<=`) compares the values of two numbers. If the number to the left is less than or equal to the number to the right, it returns `true`. If the number on the left is greater than the number on the right, it returns `false`. Like the equality operator, `less than or equal to` converts data types.
|
||||
|
||||
**例如**
|
||||
**Examples**
|
||||
|
||||
```js
|
||||
4 <= 5 // true
|
||||
@ -23,53 +23,53 @@ dashedName: comparison-with-the-less-than-or-equal-to-operator
|
||||
|
||||
# --instructions--
|
||||
|
||||
添加`小于等于`运算符到指定行,使得函数的返回语句有意义。
|
||||
Add the less than or equal to operator to the indicated lines so that the return statements make sense.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testLessOrEqual(0)`应该返回 "Smaller Than or Equal to 12"。
|
||||
`testLessOrEqual(0)` should return "Smaller Than or Equal to 12"
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(0) === 'Smaller Than or Equal to 12');
|
||||
```
|
||||
|
||||
`testLessOrEqual(11)`应该返回 "Smaller Than or Equal to 12"。
|
||||
`testLessOrEqual(11)` should return "Smaller Than or Equal to 12"
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(11) === 'Smaller Than or Equal to 12');
|
||||
```
|
||||
|
||||
`testLessOrEqual(12)`应该返回 "Smaller Than or Equal to 12"。
|
||||
`testLessOrEqual(12)` should return "Smaller Than or Equal to 12"
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(12) === 'Smaller Than or Equal to 12');
|
||||
```
|
||||
|
||||
`testLessOrEqual(23)`应该返回 "Smaller Than or Equal to 24"。
|
||||
`testLessOrEqual(23)` should return "Smaller Than or Equal to 24"
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(23) === 'Smaller Than or Equal to 24');
|
||||
```
|
||||
|
||||
`testLessOrEqual(24)`应该返回 "Smaller Than or Equal to 24"。
|
||||
`testLessOrEqual(24)` should return "Smaller Than or Equal to 24"
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(24) === 'Smaller Than or Equal to 24');
|
||||
```
|
||||
|
||||
`testLessOrEqual(25)`应该返回 "More Than 24"。
|
||||
`testLessOrEqual(25)` should return "More Than 24"
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(25) === 'More Than 24');
|
||||
```
|
||||
|
||||
`testLessOrEqual(55)`应该返回 "More Than 24"。
|
||||
`testLessOrEqual(55)` should return "More Than 24"
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(55) === 'More Than 24');
|
||||
```
|
||||
|
||||
你应该使用`<=`运算符至少两。
|
||||
You should use the `<=` operator at least twice
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*<=\s*('|")*\d+('|")*/g).length > 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d1
|
||||
title: 严格相等运算符
|
||||
title: Comparison with the Strict Equality Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cy87atr'
|
||||
forumTopicId: 16790
|
||||
@ -9,44 +9,44 @@ dashedName: comparison-with-the-strict-equality-operator
|
||||
|
||||
# --description--
|
||||
|
||||
严格相等运算符(`===`)是相对相等操作符(`==`)的另一种比较操作符。与相等操作符不同的是,它会同时比较元素的值和`数据类型`。
|
||||
Strict equality (`===`) is the counterpart to the equality operator (`==`). However, unlike the equality operator, which attempts to convert both values being compared to a common type, the strict equality operator does not perform a type conversion.
|
||||
|
||||
如果比较的值类型不同,那么在严格相等运算符比较下它们是不相等的,会返回 false 。
|
||||
If the values being compared have different types, they are considered unequal, and the strict equality operator will return false.
|
||||
|
||||
**示例**
|
||||
**Examples**
|
||||
|
||||
```js
|
||||
3 === 3 // true
|
||||
3 === '3' // false
|
||||
```
|
||||
|
||||
`3`是一个`数字`类型的,而`'3'`是一个`字符串`类型的,所以 3 不全等于 '3'。
|
||||
In the second example, `3` is a `Number` type and `'3'` is a `String` type.
|
||||
|
||||
# --instructions--
|
||||
|
||||
在`if`语句值使用严格相等运算符,这样当`val`严格等于7的时候,函数会返回"Equal"。
|
||||
Use the strict equality operator in the `if` statement so the function will return "Equal" when `val` is strictly equal to `7`
|
||||
|
||||
# --hints--
|
||||
|
||||
`testStrict(10)`应该返回 "Not Equal"。
|
||||
`testStrict(10)` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testStrict(10) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testStrict(7)`应该返回 "Equal"。
|
||||
`testStrict(7)` should return "Equal"
|
||||
|
||||
```js
|
||||
assert(testStrict(7) === 'Equal');
|
||||
```
|
||||
|
||||
`testStrict("7")`应该返回 "Not Equal"。
|
||||
`testStrict("7")` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testStrict('7') === 'Not Equal');
|
||||
```
|
||||
|
||||
你应该使用`===`运算符。
|
||||
You should use the `===` operator
|
||||
|
||||
```js
|
||||
assert(code.match(/(val\s*===\s*\d+)|(\d+\s*===\s*val)/g).length > 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d3
|
||||
title: 严格不等运算符
|
||||
title: Comparison with the Strict Inequality Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cKekkUy'
|
||||
forumTopicId: 16791
|
||||
@ -9,9 +9,9 @@ dashedName: comparison-with-the-strict-inequality-operator
|
||||
|
||||
# --description--
|
||||
|
||||
严格不相等运算符(`!==`)与全等运算符是相反的。这意味着严格不相等并返回`false`的地方,用严格相等运算符会返回`true`,*反之亦然*。严格不相等运算符不会转换值的数据类型。
|
||||
The strict inequality operator (`!==`) is the logical opposite of the strict equality operator. It means "Strictly Not Equal" and returns `false` where strict equality would return `true` and *vice versa*. Strict inequality will not convert data types.
|
||||
|
||||
**示例**
|
||||
**Examples**
|
||||
|
||||
```js
|
||||
3 !== 3 // false
|
||||
@ -21,35 +21,35 @@ dashedName: comparison-with-the-strict-inequality-operator
|
||||
|
||||
# --instructions--
|
||||
|
||||
在`if`语句中,添加严格不相等运算符`!==`,这样如果`val`与`17`严格不相等的时候,函数会返回 "Not Equal"。
|
||||
Add the strict inequality operator to the `if` statement so the function will return "Not Equal" when `val` is not strictly equal to `17`
|
||||
|
||||
# --hints--
|
||||
|
||||
`testStrictNotEqual(17)`应该返回 "Equal"。
|
||||
`testStrictNotEqual(17)` should return "Equal"
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual(17) === 'Equal');
|
||||
```
|
||||
|
||||
`testStrictNotEqual("17")`应该返回 "Not Equal"。
|
||||
`testStrictNotEqual("17")` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual('17') === 'Not Equal');
|
||||
```
|
||||
|
||||
`testStrictNotEqual(12)`应该返回 "Not Equal"。
|
||||
`testStrictNotEqual(12)` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual(12) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testStrictNotEqual("bob")`应该返回 "Not Equal"。
|
||||
`testStrictNotEqual("bob")` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual('bob') === 'Not Equal');
|
||||
```
|
||||
|
||||
应该使用 `!==` 运算符。
|
||||
You should use the `!==` operator
|
||||
|
||||
```js
|
||||
assert(code.match(/(val\s*!==\s*\d+)|(\d+\s*!==\s*val)/g).length > 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d8
|
||||
title: 逻辑与运算符
|
||||
title: Comparisons with the Logical And Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cvbRVtr'
|
||||
forumTopicId: 16799
|
||||
@ -9,9 +9,9 @@ dashedName: comparisons-with-the-logical-and-operator
|
||||
|
||||
# --description--
|
||||
|
||||
有时你需要在一次判断中做多个操作。当且仅当运算符的左边和右边都是`true`,<dfn>逻辑与</dfn> 运算符(`&&`)才会返回`true`。
|
||||
Sometimes you will need to test more than one thing at a time. The <dfn>logical and</dfn> operator (`&&`) returns `true` if and only if the <dfn>operands</dfn> to the left and right of it are true.
|
||||
|
||||
同样的效果可以通过 if 语句的嵌套来实现:
|
||||
The same effect could be achieved by nesting an if statement inside another if:
|
||||
|
||||
```js
|
||||
if (num > 5) {
|
||||
@ -22,7 +22,7 @@ if (num > 5) {
|
||||
return "No";
|
||||
```
|
||||
|
||||
只有当`num`的值在 6 和 9 之间(包括 6 和 9)才会返回 "Yes"。相同的逻辑可被写为:
|
||||
will only return "Yes" if `num` is greater than `5` and less than `10`. The same logic can be written as:
|
||||
|
||||
```js
|
||||
if (num > 5 && num < 10) {
|
||||
@ -33,65 +33,65 @@ return "No";
|
||||
|
||||
# --instructions--
|
||||
|
||||
请使用逻辑与运算符把两个 if 语句合并为一个 if 语句,如果`val`小于或等于`50`并且大于或等于`25`,返回`"Yes"`。否则,将返回`"No"`。
|
||||
Replace the two if statements with one statement, using the && operator, which will return `"Yes"` if `val` is less than or equal to `50` and greater than or equal to `25`. Otherwise, will return `"No"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
你应该使用`&&`运算符一次。
|
||||
You should use the `&&` operator once
|
||||
|
||||
```js
|
||||
assert(code.match(/&&/g).length === 1);
|
||||
```
|
||||
|
||||
你应该只有一个`if`表达式。
|
||||
You should only have one `if` statement
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length === 1);
|
||||
```
|
||||
|
||||
`testLogicalAnd(0)`应该返回 "No"。
|
||||
`testLogicalAnd(0)` should return "No"
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(0) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(24)`应该返回 "No"。
|
||||
`testLogicalAnd(24)` should return "No"
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(24) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(25)`应该返回 "Yes"。
|
||||
`testLogicalAnd(25)` should return "Yes"
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(25) === 'Yes');
|
||||
```
|
||||
|
||||
`testLogicalAnd(30)`应该返回 "Yes"。
|
||||
`testLogicalAnd(30)` should return "Yes"
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(30) === 'Yes');
|
||||
```
|
||||
|
||||
`testLogicalAnd(50)`应该返回 "Yes"。
|
||||
`testLogicalAnd(50)` should return "Yes"
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(50) === 'Yes');
|
||||
```
|
||||
|
||||
`testLogicalAnd(51)`应该返回 "No"。
|
||||
`testLogicalAnd(51)` should return "No"
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(51) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(75)`应该返回 "No"。
|
||||
`testLogicalAnd(75)` should return "No"
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(75) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(80)`应该返回 "No"。
|
||||
`testLogicalAnd(80)` should return "No"
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(80) === 'No');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d9
|
||||
title: 逻辑或运算符
|
||||
title: Comparisons with the Logical Or Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cEPrGTN'
|
||||
forumTopicId: 16800
|
||||
@ -9,11 +9,11 @@ dashedName: comparisons-with-the-logical-or-operator
|
||||
|
||||
# --description--
|
||||
|
||||
只要<dfn>逻辑或</dfn>运算符`||`两边任何一个为`true`,那么它就返回`true`;否则返回`false`。
|
||||
The <dfn>logical or</dfn> operator (`||`) returns `true` if either of the <dfn>operands</dfn> is `true`. Otherwise, it returns `false`.
|
||||
|
||||
<dfn>逻辑或</dfn>运算符由两个管道符号(|)组成。这个按键位于退格键和回车键之间。
|
||||
The <dfn>logical or</dfn> operator is composed of two pipe symbols: (`||`). This can typically be found between your Backspace and Enter keys.
|
||||
|
||||
下面这样的语句你应该很熟悉:
|
||||
The pattern below should look familiar from prior waypoints:
|
||||
|
||||
```js
|
||||
if (num > 10) {
|
||||
@ -25,7 +25,7 @@ if (num < 5) {
|
||||
return "Yes";
|
||||
```
|
||||
|
||||
只有当`num`大于等于 5 或小于等于 10 时,函数返回"Yes"。相同的逻辑可以简写成:
|
||||
will return "Yes" only if `num` is between `5` and `10` (5 and 10 included). The same logic can be written as:
|
||||
|
||||
```js
|
||||
if (num > 10 || num < 5) {
|
||||
@ -36,65 +36,65 @@ return "Yes";
|
||||
|
||||
# --instructions--
|
||||
|
||||
请使用逻辑或运算符把两个 if 语句合并为一个 if 语句,如果`val`不在 10 和 20 之间(包括 10 和 20),返回`"Outside"`。反之,返回`"Inside"`。
|
||||
Combine the two `if` statements into one statement which returns `"Outside"` if `val` is not between `10` and `20`, inclusive. Otherwise, return `"Inside"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
你应该使用一次`||`操作符。
|
||||
You should use the `||` operator once
|
||||
|
||||
```js
|
||||
assert(code.match(/\|\|/g).length === 1);
|
||||
```
|
||||
|
||||
你应该只有一个`if`表达式。
|
||||
You should only have one `if` statement
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length === 1);
|
||||
```
|
||||
|
||||
`testLogicalOr(0)`应该返回 "Outside"。
|
||||
`testLogicalOr(0)` should return "Outside"
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(0) === 'Outside');
|
||||
```
|
||||
|
||||
`testLogicalOr(9)`应该返回 "Outside"。
|
||||
`testLogicalOr(9)` should return "Outside"
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(9) === 'Outside');
|
||||
```
|
||||
|
||||
`testLogicalOr(10)`应该返回 "Inside"。
|
||||
`testLogicalOr(10)` should return "Inside"
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(10) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(15)`应该返回 "Inside"。
|
||||
`testLogicalOr(15)` should return "Inside"
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(15) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(19)`应该返回 "Inside"。
|
||||
`testLogicalOr(19)` should return "Inside"
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(19) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(20)`应该返回 "Inside"。
|
||||
`testLogicalOr(20)` should return "Inside"
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(20) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(21)`应该返回 "Outside"。
|
||||
`testLogicalOr(21)` should return "Outside"
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(21) === 'Outside');
|
||||
```
|
||||
|
||||
`testLogicalOr(25)`应该返回 "Outside"。
|
||||
`testLogicalOr(25)` should return "Outside"
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(25) === 'Outside');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244af
|
||||
title: 复合赋值之 +=
|
||||
title: Compound Assignment With Augmented Addition
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDR6LCb'
|
||||
forumTopicId: 16661
|
||||
@ -9,13 +9,13 @@ dashedName: compound-assignment-with-augmented-addition
|
||||
|
||||
# --description--
|
||||
|
||||
在编程当中,通常通过赋值来修改变量的内容。记住,赋值时 Javascript 会先计算`=`右边的内容,所以我们可以写这样的语句:
|
||||
In programming, it is common to use assignments to modify the contents of a variable. Remember that everything to the right of the equals sign is evaluated first, so we can say:
|
||||
|
||||
`myVar = myVar + 5;`
|
||||
|
||||
以上是最常见的运算赋值语句,即先运算、再赋值。还有一类操作符是一步到位既做运算也赋值的。
|
||||
to add `5` to `myVar`. Since this is such a common pattern, there are operators which do both a mathematical operation and assignment in one step.
|
||||
|
||||
其中一种就是`+=`运算符。
|
||||
One such operator is the `+=` operator.
|
||||
|
||||
```js
|
||||
var myVar = 1;
|
||||
@ -25,35 +25,35 @@ console.log(myVar); // Returns 6
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用`+=`操作符实现同样的效果。
|
||||
Convert the assignments for `a`, `b`, and `c` to use the `+=` operator.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a`应该等于`15`。
|
||||
`a` should equal `15`.
|
||||
|
||||
```js
|
||||
assert(a === 15);
|
||||
```
|
||||
|
||||
`b`应该等于`26`。
|
||||
`b` should equal `26`.
|
||||
|
||||
```js
|
||||
assert(b === 26);
|
||||
```
|
||||
|
||||
`c`应该等于`19`。
|
||||
`c` should equal `19`.
|
||||
|
||||
```js
|
||||
assert(c === 19);
|
||||
```
|
||||
|
||||
你应该对每个变量使用`+=`操作符。
|
||||
You should use the `+=` operator for each variable.
|
||||
|
||||
```js
|
||||
assert(code.match(/\+=/g).length === 3);
|
||||
```
|
||||
|
||||
不要修改注释上面的代码。
|
||||
You should not modify the code above the specified comment.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b2
|
||||
title: 复合赋值之 /=
|
||||
title: Compound Assignment With Augmented Division
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QvKT2'
|
||||
forumTopicId: 16659
|
||||
@ -9,45 +9,45 @@ dashedName: compound-assignment-with-augmented-division
|
||||
|
||||
# --description--
|
||||
|
||||
`/=`操作符是让变量与另一个数相除并赋值。
|
||||
The `/=` operator divides a variable by another number.
|
||||
|
||||
`myVar = myVar / 5;`
|
||||
|
||||
变量`myVar`等于自身除以`5`的值。等价于:
|
||||
Will divide `myVar` by `5`. This can be rewritten as:
|
||||
|
||||
`myVar /= 5;`
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用`/=`操作符实现同样的效果。
|
||||
Convert the assignments for `a`, `b`, and `c` to use the `/=` operator.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a`应该等于`4`。
|
||||
`a` should equal `4`.
|
||||
|
||||
```js
|
||||
assert(a === 4);
|
||||
```
|
||||
|
||||
`b`应该等于`27`。
|
||||
`b` should equal `27`.
|
||||
|
||||
```js
|
||||
assert(b === 27);
|
||||
```
|
||||
|
||||
`c`应该等于`3`。
|
||||
`c` should equal `3`.
|
||||
|
||||
```js
|
||||
assert(c === 3);
|
||||
```
|
||||
|
||||
应该对每个变量使用`/=`操作符。
|
||||
You should use the `/=` operator for each variable.
|
||||
|
||||
```js
|
||||
assert(code.match(/\/=/g).length === 3);
|
||||
```
|
||||
|
||||
不要修改注释上面的代码。
|
||||
You should not modify the code above the specified comment.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b1
|
||||
title: 复合赋值之 *=
|
||||
title: Compound Assignment With Augmented Multiplication
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c83vrfa'
|
||||
forumTopicId: 16662
|
||||
@ -9,45 +9,45 @@ dashedName: compound-assignment-with-augmented-multiplication
|
||||
|
||||
# --description--
|
||||
|
||||
`*=`操作符是让变量与一个数相乘并赋值。
|
||||
The `*=` operator multiplies a variable by a number.
|
||||
|
||||
`myVar = myVar * 5;`
|
||||
|
||||
变量`myVar`等于自身与数值`5`相乘的值。也可以写作这样的形式:
|
||||
will multiply `myVar` by `5`. This can be rewritten as:
|
||||
|
||||
`myVar *= 5;`
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用`*=`操作符实现同样的效果。
|
||||
Convert the assignments for `a`, `b`, and `c` to use the `*=` operator.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a`应该等于`25`。
|
||||
`a` should equal `25`.
|
||||
|
||||
```js
|
||||
assert(a === 25);
|
||||
```
|
||||
|
||||
`b`应该等于`36`。
|
||||
`b` should equal `36`.
|
||||
|
||||
```js
|
||||
assert(b === 36);
|
||||
```
|
||||
|
||||
`c`应该等于`46`。
|
||||
`c` should equal `46`.
|
||||
|
||||
```js
|
||||
assert(c === 46);
|
||||
```
|
||||
|
||||
应该对每个变量使用`*=`操作符。
|
||||
You should use the `*=` operator for each variable.
|
||||
|
||||
```js
|
||||
assert(code.match(/\*=/g).length === 3);
|
||||
```
|
||||
|
||||
不要修改注释上面的代码。
|
||||
You should not modify the code above the specified comment.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b0
|
||||
title: 复合赋值之 -=
|
||||
title: Compound Assignment With Augmented Subtraction
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2Qv7AV'
|
||||
forumTopicId: 16660
|
||||
@ -9,45 +9,45 @@ dashedName: compound-assignment-with-augmented-subtraction
|
||||
|
||||
# --description--
|
||||
|
||||
与`+=`操作符类似,`-=`操作符用来对一个变量进行减法赋值操作。
|
||||
Like the `+=` operator, `-=` subtracts a number from a variable.
|
||||
|
||||
`myVar = myVar - 5;`
|
||||
|
||||
变量`myVar`等于自身减去`5`的值。也可以写成这种形式:
|
||||
will subtract `5` from `myVar`. This can be rewritten as:
|
||||
|
||||
`myVar -= 5;`
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用`-=`操作符实现同样的效果。
|
||||
Convert the assignments for `a`, `b`, and `c` to use the `-=` operator.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a`应该等于`5`。
|
||||
`a` should equal `5`.
|
||||
|
||||
```js
|
||||
assert(a === 5);
|
||||
```
|
||||
|
||||
`b`应该等于`-6`。
|
||||
`b` should equal `-6`.
|
||||
|
||||
```js
|
||||
assert(b === -6);
|
||||
```
|
||||
|
||||
`c`应该等于`2`。
|
||||
`c` should equal `2`.
|
||||
|
||||
```js
|
||||
assert(c === 2);
|
||||
```
|
||||
|
||||
应该对每个变量使用`-=`操作符。
|
||||
You should use the `-=` operator for each variable.
|
||||
|
||||
```js
|
||||
assert(code.match(/-=/g).length === 3);
|
||||
```
|
||||
|
||||
不要修改注释上面的代码。
|
||||
You should not modify the code above the specified comment.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b7
|
||||
title: 用加号运算符连接字符串
|
||||
title: Concatenating Strings with Plus Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNpM8AN'
|
||||
forumTopicId: 16802
|
||||
@ -9,42 +9,49 @@ dashedName: concatenating-strings-with-plus-operator
|
||||
|
||||
# --description--
|
||||
|
||||
在 JavaScript 中,当对一个`String`类型的值使用`+`操作符的时候,它被称作 <dfn>拼接操作符</dfn>。你可以通过<dfn>拼接</dfn>其他字符串来创建一个新的字符串。
|
||||
In JavaScript, when the `+` operator is used with a `String` value, it is called the <dfn>concatenation</dfn> operator. You can build a new string out of other strings by <dfn>concatenating</dfn> them together.
|
||||
|
||||
**示例**
|
||||
**Example**
|
||||
|
||||
```js
|
||||
'My name is Alan,' + ' I concatenate.'
|
||||
```
|
||||
|
||||
**提示**
|
||||
注意空格。拼接操作不会在两个字符串之间添加空格,所以想加上空格的话,你需要自己在字符串里面添加。
|
||||
**Note**
|
||||
Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
var ourStr = "I come first. " + "I come second.";
|
||||
// ourStr is "I come first. I come second."
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用`+`操作符,把字符串`"This is the start. "`和`"This is the end."`连接起来并赋值给变量`myStr`。
|
||||
Build `myStr` from the strings `"This is the start. "` and `"This is the end."` using the `+` operator.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr`的值应该是`This is the start. This is the end.`。
|
||||
`myStr` should have a value of `This is the start. This is the end.`
|
||||
|
||||
```js
|
||||
assert(myStr === 'This is the start. This is the end.');
|
||||
```
|
||||
|
||||
使用`+`操作符构建`myStr`。
|
||||
You should use the `+` operator to build `myStr`.
|
||||
|
||||
```js
|
||||
assert(code.match(/(["']).*(["'])\s*\+\s*(["']).*(["'])/g).length > 1);
|
||||
assert(code.match(/(["']).*\1\s*\+\s*(["']).*\2/g));
|
||||
```
|
||||
|
||||
`myStr`应该被`var`关键字声明。
|
||||
`myStr` should be created using the `var` keyword.
|
||||
|
||||
```js
|
||||
assert(/var\s+myStr/.test(code));
|
||||
```
|
||||
|
||||
确保有给`myStr`赋值。
|
||||
You should assign the result to the `myStr` variable.
|
||||
|
||||
```js
|
||||
assert(/myStr\s*=/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b8
|
||||
title: 用 += 运算符连接字符串
|
||||
title: Concatenating Strings with the Plus Equals Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cbQmmC4'
|
||||
forumTopicId: 16803
|
||||
@ -9,31 +9,35 @@ dashedName: concatenating-strings-with-the-plus-equals-operator
|
||||
|
||||
# --description--
|
||||
|
||||
我们还可以使用`+=`运算符来<dfn>concatenate</dfn>(拼接)字符串到现有字符串的结尾。对于那些被分割成几段的长的字符串来说,这一操作是非常有用的。
|
||||
We can also use the `+=` operator to <dfn>concatenate</dfn> a string onto the end of an existing string variable. This can be very helpful to break a long string over several lines.
|
||||
|
||||
**提示**
|
||||
注意空格。拼接操作不会在两个字符串之间添加空格,所以如果想要加上空格的话,你需要自己在字符串里面添加。
|
||||
**Note**
|
||||
Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
var ourStr = "I come first. ";
|
||||
ourStr += "I come second.";
|
||||
// ourStr is now "I come first. I come second."
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
通过使用`+=`操作符来连接这两个字符串:
|
||||
`"This is the first sentence. "`和`"This is the second sentence."`并赋给变量`myStr`。
|
||||
Build `myStr` over several lines by concatenating these two strings: `"This is the first sentence. "` and `"This is the second sentence."` using the `+=` operator. Use the `+=` operator similar to how it is shown in the editor. Start by assigning the first string to `myStr`, then add on the second string.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr`的值应该是`This is the first sentence. This is the second sentence.`。
|
||||
`myStr` should have a value of `This is the first sentence. This is the second sentence.`
|
||||
|
||||
```js
|
||||
assert(myStr === 'This is the first sentence. This is the second sentence.');
|
||||
```
|
||||
|
||||
使用`+=`操作符创建`myStr`变量。
|
||||
You should use the `+=` operator to build `myStr`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(/\w\s*\+=\s*["']/g).length > 1 &&
|
||||
code.match(/\w\s*\=\s*["']/g).length > 1
|
||||
);
|
||||
assert(code.match(/myStr\s*\+=\s*(["']).*\1/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b9
|
||||
title: 用变量构造字符串
|
||||
title: Constructing Strings with Variables
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cqk8rf4'
|
||||
forumTopicId: 16805
|
||||
@ -9,21 +9,29 @@ dashedName: constructing-strings-with-variables
|
||||
|
||||
# --description--
|
||||
|
||||
有时候你需要创建一个类似[Mad Libs](https://en.wikipedia.org/wiki/Mad_Libs)(填词游戏)风格的字符串。通过使用连接运算符`+`,你可以插入一个或多个变量来组成一个字符串。
|
||||
Sometimes you will need to build a string, [Mad Libs](https://en.wikipedia.org/wiki/Mad_Libs) style. By using the concatenation operator (`+`), you can insert one or more variables into a string you're building.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
var ourName = "freeCodeCamp";
|
||||
var ourStr = "Hello, our name is " + ourName + ", how are you?";
|
||||
// ourStr is now "Hello, our name is freeCodeCamp, how are you?"
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
把你的名字赋值给变量`myName`,然后把变量`myName`插入到字符串`"My name is "`和`" and I am well!"`之间,并把连接后的结果赋值给变量`myStr`。
|
||||
Set `myName` to a string equal to your name and build `myStr` with `myName` between the strings `"My name is "` and `" and I am well!"`
|
||||
|
||||
# --hints--
|
||||
|
||||
`myName`至少要包含三个字符。
|
||||
`myName` should be set to a string at least 3 characters long.
|
||||
|
||||
```js
|
||||
assert(typeof myName !== 'undefined' && myName.length > 2);
|
||||
```
|
||||
|
||||
使用两个`+`操作符创建包含`myName`的`myStr`变量。
|
||||
You should use two `+` operators to build `myStr` with `myName` inside it.
|
||||
|
||||
```js
|
||||
assert(code.match(/["']\s*\+\s*myName\s*\+\s*["']/g).length > 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56105e7b514f539506016a5e
|
||||
title: 使用 For 循环反向遍历数组
|
||||
title: Count Backwards With a For Loop
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2R6BHa'
|
||||
forumTopicId: 16808
|
||||
@ -9,40 +9,40 @@ dashedName: count-backwards-with-a-for-loop
|
||||
|
||||
# --description--
|
||||
|
||||
for循环也可以逆向迭代,只要我们定义好合适的条件。
|
||||
A for loop can also count backwards, so long as we can define the right conditions.
|
||||
|
||||
为了让每次倒数递减 2,我们需要改变我们的`初始化`,`条件判断`和`计数器`。
|
||||
In order to decrement by two each iteration, we'll need to change our `initialization`, `condition`, and `final-expression`.
|
||||
|
||||
我们让`i = 10`,并且当`i > 0`的时候才继续循环。我们使用`i -= 2`来让`i`每次循环递减 2。
|
||||
We'll start at `i = 10` and loop while `i > 0`. We'll decrement `i` by 2 each loop with `i -= 2`.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i=10; i > 0; i-=2) {
|
||||
for (var i = 10; i > 0; i -= 2) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
循环结束后,`ourArray`的值为`[10,8,6,4,2]`。 让我们改变`初始化`和`计数器`,这样我们就可以按照奇数从后往前两两倒着数。
|
||||
`ourArray` will now contain `[10,8,6,4,2]`. Let's change our `initialization` and `final-expression` so we can count backward by twos by odd numbers.
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用一个`for`循环,把 9 到 1 的奇数添加进`myArray`。
|
||||
Push the odd numbers from 9 through 1 to `myArray` using a `for` loop.
|
||||
|
||||
# --hints--
|
||||
|
||||
你应该使用`for`循环。
|
||||
You should be using a `for` loop for this.
|
||||
|
||||
```js
|
||||
assert(code.match(/for\s*\(/g).length > 1);
|
||||
assert(/for\s*\([^)]+?\)/.test(code));
|
||||
```
|
||||
|
||||
你应该使用数组方法`push`。
|
||||
You should be using the array method `push`.
|
||||
|
||||
```js
|
||||
assert(code.match(/myArray.push/));
|
||||
```
|
||||
|
||||
`myArray`应该等于`[9,7,5,3,1]`。
|
||||
`myArray` should equal `[9,7,5,3,1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [9, 7, 5, 3, 1]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 565bbe00e9cc8ac0725390f4
|
||||
title: 21点游戏
|
||||
title: Counting Cards
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c6KE7ty'
|
||||
forumTopicId: 16809
|
||||
@ -9,22 +9,25 @@ dashedName: counting-cards
|
||||
|
||||
# --description--
|
||||
|
||||
在赌场 21 点游戏中,玩家可以通过计算牌桌上已经发放的卡牌的高低值来让自己在游戏中保持优势,这就叫[21 点算法](https://www.douban.com/note/273781969/)。
|
||||
In the casino game Blackjack, a player can gain an advantage over the house by keeping track of the relative number of high and low cards remaining in the deck. This is called [Card Counting](https://en.wikipedia.org/wiki/Card_counting).
|
||||
|
||||
根据下面的表格,每张卡牌都分配了一个值。如果卡牌的值大于 0,那么玩家应该追加赌注。反之,追加少许赌注甚至不追加赌注。
|
||||
Having more high cards remaining in the deck favors the player. Each card is assigned a value according to the table below. When the count is positive, the player should bet high. When the count is zero or negative, the player should bet low.
|
||||
|
||||
<table class='table table-striped'><thead><tr><th>Count Change</th><th>Cards</th></tr></thead><tbody><tr><td>+1</td><td>2, 3, 4, 5, 6</td></tr><tr><td>0</td><td>7, 8, 9</td></tr><tr><td>-1</td><td>10, 'J', 'Q', 'K', 'A'</td></tr></tbody></table>
|
||||
你需要写一个函数实现 21 点算法,它根据参数<code>card</code>的值来递增或递减变量<code>count</code>,函数返回一个由当前<code>count</code>和<code>Bet</code>(<code>count>0</code>)或<code>Hold</code>(<code>count<=0</code>)拼接的字符串。注意<code>count</code>和<code>"Bet"</code>或<code>Hold</code>应该用空格分开。</count>
|
||||
|
||||
**例如:**
|
||||
<code>-3 Hold<br>5 Bet</code>
|
||||
You will write a card counting function. It will receive a `card` parameter, which can be a number or a string, and increment or decrement the global `count` variable according to the card's value (see table). The function will then return a string with the current count and the string `Bet` if the count is positive, or `Hold` if the count is zero or negative. The current count and the player's decision (`Bet` or `Hold`) should be separated by a single space.
|
||||
|
||||
**提示**
|
||||
既然 card 的值为 7、8、9 时,count 值不变,那我们就可以忽略这种情况。
|
||||
**Example Output**
|
||||
`-3 Hold`
|
||||
`5 Bet`
|
||||
|
||||
**Hint**
|
||||
Do NOT reset `count` to 0 when value is 7, 8, or 9. Do NOT return an array.
|
||||
Do NOT include quotes (single or double) in the output.
|
||||
|
||||
# --hints--
|
||||
|
||||
Cards Sequence 2, 3, 4, 5, 6 应该返回`5 Bet`。
|
||||
Cards Sequence 2, 3, 4, 5, 6 should return `5 Bet`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -43,7 +46,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 7, 8, 9 应该返回 `0 Hold`。
|
||||
Cards Sequence 7, 8, 9 should return `0 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -60,7 +63,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 10, J, Q, K, A 应该返回 `-5 Hold`。
|
||||
Cards Sequence 10, J, Q, K, A should return `-5 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -79,7 +82,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 3, 7, Q, 8, A 应该返回 `-1 Hold`。
|
||||
Cards Sequence 3, 7, Q, 8, A should return `-1 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -98,7 +101,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 2, J, 9, 2, 7 应该返回 `1 Bet`。
|
||||
Cards Sequence 2, J, 9, 2, 7 should return `1 Bet`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -117,7 +120,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 2, 2, 10 应该返回 `1 Bet`。
|
||||
Cards Sequence 2, 2, 10 should return `1 Bet`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -134,7 +137,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 3, 2, A, 10, K 应该返回 `-1 Hold`。
|
||||
Cards Sequence 3, 2, A, 10, K should return `-1 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1391c1c11feddfaeb4bdef
|
||||
title: 创建一个小数
|
||||
title: Create Decimal Numbers with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ca8GEuW'
|
||||
forumTopicId: 16826
|
||||
@ -9,24 +9,24 @@ dashedName: create-decimal-numbers-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
我们也可以把小数存储到变量中。小数也被称作<dfn>浮点数</dfn> 。
|
||||
We can store decimal numbers in variables too. Decimal numbers are sometimes referred to as <dfn>floating point</dfn> numbers or <dfn>floats</dfn>.
|
||||
|
||||
**提示**
|
||||
不是所有的实数都可以用 <dfn>浮点数</dfn> 来表示。因为可能存在四舍五入的错误,[详情查看](https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems)。
|
||||
**Note**
|
||||
Not all real numbers can accurately be represented in <dfn>floating point</dfn>. This can lead to rounding errors. [Details Here](https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems).
|
||||
|
||||
# --instructions--
|
||||
|
||||
创建一个变量`myDecimal`并给它赋值一个浮点数。(例如`5.21`)。
|
||||
Create a variable `myDecimal` and give it a decimal value with a fractional part (e.g. `5.7`).
|
||||
|
||||
# --hints--
|
||||
|
||||
`myDecimal`应该是一个数字。
|
||||
`myDecimal` should be a number.
|
||||
|
||||
```js
|
||||
assert(typeof myDecimal === 'number');
|
||||
```
|
||||
|
||||
`myDecimal`应该包含小数点。
|
||||
`myDecimal` should have a decimal point
|
||||
|
||||
```js
|
||||
assert(myDecimal % 1 != 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7123c9c443eddfaeb5bdef
|
||||
title: 声明变量
|
||||
title: Declare JavaScript Variables
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNanrHq'
|
||||
forumTopicId: 17556
|
||||
@ -9,38 +9,35 @@ dashedName: declare-javascript-variables
|
||||
|
||||
# --description--
|
||||
|
||||
在计算机科学中,<dfn>数据</dfn>就是一切,它对于计算机意义重大。JavaScript 提供七种不同的<dfn>数据类型</dfn>,它们是`undefined`(未定义), `null`(空),`boolean`(布尔型),`string`(字符串),`symbol`(符号),`number`(数字),和`object`(对象)。
|
||||
In computer science, <dfn>data</dfn> is anything that is meaningful to the computer. JavaScript provides eight different <dfn>data types</dfn> which are `undefined`, `null`, `boolean`, `string`, `symbol`, `bigint`, `number`, and `object`.
|
||||
|
||||
例如,计算机区分数字和字符集合的字符串,例如数字`12`和字符串`"12"`,`"dog"`或`"123 cats"`。计算机可以对数字执行数学运算,但不能对字符串执行数学运算。
|
||||
For example, computers distinguish between numbers, such as the number `12`, and `strings`, such as `"12"`, `"dog"`, or `"123 cats"`, which are collections of characters. Computers can perform mathematical operations on a number, but not on a string.
|
||||
|
||||
<dfn>变量</dfn>允许计算机以一种动态的形式来存储和操作数据,通过操作指向数据的指针而不是数据本身来避免了内存泄露,以上的七种数据类型都可以存储到一个变量中。
|
||||
<dfn>Variables</dfn> allow computers to store and manipulate data in a dynamic fashion. They do this by using a "label" to point to the data rather than using the data itself. Any of the eight data types may be stored in a variable.
|
||||
|
||||
`变量`非常类似于你在数学中使用的 x,y 变量,都是以一个简单命名的名称来代替我们赋值给它的数据。计算机中的`变量`与数学中的变量不同的是,计算机可以在不同的时间存储不同类型的变量。
|
||||
`Variables` are similar to the x and y variables you use in mathematics, which means they're a simple name to represent the data we want to refer to. Computer `variables` differ from mathematical variables in that they can store different values at different times.
|
||||
|
||||
通过在变量的前面使用关键字`var`,声明一个变量,例如:
|
||||
We tell JavaScript to create or <dfn>declare</dfn> a variable by putting the keyword `var` in front of it, like so:
|
||||
|
||||
```js
|
||||
var ourName;
|
||||
```
|
||||
|
||||
上面代码的意思是创建一个名为`ourName`的`变量`,在 JavaScript 中我们以分号结束语句。 `变量`名称可以由数字、字母、美元符号`$` 或者 下划线`_`组成,但是不能包含空格或者以数字为开头。
|
||||
creates a `variable` called `ourName`. In JavaScript we end statements with semicolons. `Variable` names can be made up of numbers, letters, and `$` or `_`, but may not contain spaces or start with a number.
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用`var` 关键字来创建一个名为`myName`的变量。
|
||||
Use the `var` keyword to create a variable called `myName`.
|
||||
|
||||
**提示**
|
||||
如果遇到困难了,请看下`ourName`的例子是怎么写的。
|
||||
**Hint**
|
||||
Look at the `ourName` example above if you get stuck.
|
||||
|
||||
# --hints--
|
||||
|
||||
你需要使用`var`关键字定义一个变量`myName`,并使用分号结尾。
|
||||
You should declare `myName` with the `var` keyword, ending with a semicolon
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var\s+myName\s*;/.test(code),
|
||||
'你需要使用<code>var</code>关键字定义一个变量<code>myName</code>。并使用分号结尾。'
|
||||
);
|
||||
assert(/var\s+myName\s*;/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@ -52,7 +49,6 @@ if(typeof myName !== "undefined"){(function(v){return v;})(myName);}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
```
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7123c9c444eddfaeb5bdef
|
||||
title: 声明字符串变量
|
||||
title: Declare String Variables
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QvWU6'
|
||||
forumTopicId: 17557
|
||||
@ -9,19 +9,19 @@ dashedName: declare-string-variables
|
||||
|
||||
# --description--
|
||||
|
||||
之前我们写过这样的代码:
|
||||
Previously we have used the code
|
||||
|
||||
`var myName = "your name";`
|
||||
|
||||
`"your name"`被称作<dfn>字符串变量</dfn>。字符串是用单引号或双引号包裹起来的一连串的零个或多个字符。
|
||||
`"your name"` is called a <dfn>string</dfn> <dfn>literal</dfn>. It is a string because it is a series of zero or more characters enclosed in single or double quotes.
|
||||
|
||||
# --instructions--
|
||||
|
||||
创建两个新的`字符串变量`:`myFirstName`和`myLastName`,并用你的姓和名分别为它们赋值。
|
||||
Create two new `string` variables: `myFirstName` and `myLastName` and assign them the values of your first and last name, respectively.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myFirstName`应该是一个字符串,并且至少包含一个字符。
|
||||
`myFirstName` should be a string with at least one character in it.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -39,7 +39,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myLastName`应该是一个字符串,并且至少包含一个字符。
|
||||
`myLastName` should be a string with at least one character in it.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -66,7 +66,6 @@ if(typeof myFirstName !== "undefined" && typeof myLastName !== "undefined"){(fun
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
```
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ad
|
||||
title: 数字递减
|
||||
title: Decrement a Number with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cM2KeS2'
|
||||
forumTopicId: 17558
|
||||
@ -9,30 +9,30 @@ dashedName: decrement-a-number-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
使用自减符号`--`,你可以很方便地对一个变量执行<dfn>自减</dfn>或者`-1`运算。
|
||||
You can easily <dfn>decrement</dfn> or decrease a variable by one with the `--` operator.
|
||||
|
||||
`i--;`
|
||||
|
||||
等效于
|
||||
is the equivalent of
|
||||
|
||||
`i = i - 1;`
|
||||
|
||||
**提示**
|
||||
`i--;`这种写法,省去了书写`=`符号的必要。
|
||||
**Note**
|
||||
The entire line becomes `i--;`, eliminating the need for the equal sign.
|
||||
|
||||
# --instructions--
|
||||
|
||||
重写代码,使用`--`符号对`myVar`执行自减操作。
|
||||
Change the code to use the `--` operator on `myVar`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myVar`应该等于`10`。
|
||||
`myVar` should equal `10`.
|
||||
|
||||
```js
|
||||
assert(myVar === 10);
|
||||
```
|
||||
|
||||
`myVar = myVar - 1;`语句应该被修改。
|
||||
`myVar = myVar - 1;` should be changed.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -40,13 +40,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
对`myVar`使用`--`运算符。
|
||||
You should use the `--` operator on `myVar`.
|
||||
|
||||
```js
|
||||
assert(/[-]{2}\s*myVar|myVar\s*[-]{2}/.test(code));
|
||||
```
|
||||
|
||||
不要修改注释上面的代码。
|
||||
You should not change code above the specified comment.
|
||||
|
||||
```js
|
||||
assert(/var myVar = 11;/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d3
|
||||
title: 删除对象的属性
|
||||
title: Delete Properties from a JavaScript Object
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDqKdTv'
|
||||
forumTopicId: 17560
|
||||
@ -9,26 +9,51 @@ dashedName: delete-properties-from-a-javascript-object
|
||||
|
||||
# --description--
|
||||
|
||||
我们同样可以删除对象的属性,例如:
|
||||
We can also delete properties from objects like this:
|
||||
|
||||
`delete ourDog.bark;`
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
var ourDog = {
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"],
|
||||
"bark": "bow-wow"
|
||||
};
|
||||
|
||||
delete ourDog.bark;
|
||||
```
|
||||
|
||||
After the last line shown above, `ourDog` looks like:
|
||||
|
||||
```js
|
||||
{
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"]
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
删除`myDog`对象的`"tails"`属性。
|
||||
Delete the `"tails"` property from `myDog`. You may use either dot or bracket notation.
|
||||
|
||||
# --hints--
|
||||
|
||||
从`myDog`中删除`"tails"`属性。
|
||||
You should delete the property `"tails"` from `myDog`.
|
||||
|
||||
```js
|
||||
assert(typeof myDog === 'object' && myDog.tails === undefined);
|
||||
```
|
||||
|
||||
不要修改`myDog`的初始化。
|
||||
You should not modify the `myDog` setup.
|
||||
|
||||
```js
|
||||
assert(code.match(/"tails": 1/g).length > 1);
|
||||
assert(code.match(/"tails": 1/g).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7993c9ca9feddfaeb7bdef
|
||||
title: 两个小数相除
|
||||
title: Divide One Decimal by Another with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBZe9AW'
|
||||
forumTopicId: 18255
|
||||
@ -9,27 +9,27 @@ dashedName: divide-one-decimal-by-another-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
现在让我们将一个小数除以另一个小数。
|
||||
Now let's divide one decimal by another.
|
||||
|
||||
# --instructions--
|
||||
|
||||
改变数值`0.0`的值让变量`quotient`的值等于`2.2`.
|
||||
Change the `0.0` so that `quotient` will equal to `2.2`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`quotient`的值应该等于`2.2`。
|
||||
The variable `quotient` should equal `2.2`
|
||||
|
||||
```js
|
||||
assert(quotient === 2.2);
|
||||
```
|
||||
|
||||
使用`/`运算符将 4.4 除以 2。
|
||||
You should use the `/` operator to divide 4.4 by 2
|
||||
|
||||
```js
|
||||
assert(/4\.40*\s*\/\s*2\.*0*/.test(code));
|
||||
```
|
||||
|
||||
quotient 变量应该只被赋值一次。
|
||||
The quotient variable should only be assigned once
|
||||
|
||||
```js
|
||||
assert(code.match(/quotient/g).length === 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb6bdef
|
||||
title: 除法运算
|
||||
title: Divide One Number by Another with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cqkbdAr'
|
||||
forumTopicId: 17566
|
||||
@ -9,11 +9,11 @@ dashedName: divide-one-number-by-another-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
我们可以在 JavaScript 中做除法运算。
|
||||
We can also divide one number by another.
|
||||
|
||||
JavaScript 中使用`/`符号做除法运算。
|
||||
JavaScript uses the `/` symbol for division.
|
||||
|
||||
**示例**
|
||||
**Example**
|
||||
|
||||
```js
|
||||
myVar = 16 / 2; // assigned 8
|
||||
@ -21,17 +21,17 @@ myVar = 16 / 2; // assigned 8
|
||||
|
||||
# --instructions--
|
||||
|
||||
改变数值`0`来让变量`quotient`的值等于`2`。
|
||||
Change the `0` so that the `quotient` is equal to `2`.
|
||||
|
||||
# --hints--
|
||||
|
||||
要使`quotient`的值等于 2。
|
||||
The variable `quotient` should be equal to 2.
|
||||
|
||||
```js
|
||||
assert(quotient === 2);
|
||||
```
|
||||
|
||||
使用`/`运算符。
|
||||
You should use the `/` operator.
|
||||
|
||||
```js
|
||||
assert(/\d+\s*\/\s*\d+/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b6
|
||||
title: 字符串中的转义序列
|
||||
title: Escape Sequences in Strings
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cvmqRh6'
|
||||
forumTopicId: 17567
|
||||
@ -9,33 +9,36 @@ dashedName: escape-sequences-in-strings
|
||||
|
||||
# --description--
|
||||
|
||||
引号不是字符串中唯一可以被<dfn>转义</dfn>的字符。使用转义字符有两个原因:首先是可以让你使用无法输入的字符,例如退格。其次是可以让你在一个字符串中表示多个引号,而不会出错。我们在之前的挑战中学到了这个。
|
||||
Quotes are not the only characters that can be <dfn>escaped</dfn> inside a string. There are two reasons to use escaping characters:
|
||||
|
||||
<table class='table table-striped'><thead><tr><th>代码</th><th>输出</th></tr></thead><tbody><tr><td><code>\'</code></td><td>单引号</td></tr><tr><td><code>\"</code></td><td>双引号</td></tr><tr><td><code>\\</code></td><td>反斜杠</td></tr><tr><td><code>\n</code></td><td>换行符</td></tr><tr><td><code>\r</code></td><td>回车符</td></tr><tr><td><code>\t</code></td><td>制表符</td></tr><tr><td><code>\b</code></td><td>退格</td></tr><tr><td><code>\f</code></td><td>换页符</td></tr></tbody></table>
|
||||
1. To allow you to use characters you may not otherwise be able to type out, such as a carriage return.
|
||||
2. To allow you to represent multiple quotes in a string without JavaScript misinterpreting what you mean.
|
||||
|
||||
*请注意,必须对反斜杠本身进行转义才能显示为反斜杠。*
|
||||
We learned this in the previous challenge.
|
||||
|
||||
<table class='table table-striped'><thead><tr><th>Code</th><th>Output</th></tr></thead><tbody><tr><td><code>\'</code></td><td>single quote</td></tr><tr><td><code>\"</code></td><td>double quote</td></tr><tr><td><code>\\</code></td><td>backslash</td></tr><tr><td><code>\n</code></td><td>newline</td></tr><tr><td><code>\r</code></td><td>carriage return</td></tr><tr><td><code>\t</code></td><td>tab</td></tr><tr><td><code>\b</code></td><td>word boundary</td></tr><tr><td><code>\f</code></td><td>form feed</td></tr></tbody></table>
|
||||
|
||||
*Note that the backslash itself must be escaped in order to display as a backslash.*
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用转义字符将下面三行文本字符串赋给变量`myStr`。
|
||||
Assign the following three lines of text into the single variable `myStr` using escape sequences.
|
||||
|
||||
<blockquote>FirstLine<br> \SecondLine<br>ThirdLine</blockquote>
|
||||
|
||||
你需要使用转义字符正确地插入特殊字符,确保间距与上面文本一致并且单词或转义字符之间没有空格。
|
||||
You will need to use escape sequences to insert special characters correctly. You will also need to follow the spacing as it looks above, with no spaces between escape sequences or words.
|
||||
|
||||
像这样用转义字符写出来:
|
||||
|
||||
"FirstLine```换行符``制表符``反斜杠```SecondLine`换行符`ThirdLine"
|
||||
**Note:** The indentation for `SecondLine` is achieved with the tab escape character, not spaces.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr`不能包含空格。
|
||||
`myStr` should not contain any spaces
|
||||
|
||||
```js
|
||||
assert(!/ /.test(myStr));
|
||||
```
|
||||
|
||||
`myStr`应该包含字符串`FirstLine`, `SecondLine` and `ThirdLine` (记得区分大小写)。
|
||||
`myStr` should contain the strings `FirstLine`, `SecondLine` and `ThirdLine` (remember case sensitivity)
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -43,31 +46,31 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`FirstLine`后面应该是一个新行`\n`。
|
||||
`FirstLine` should be followed by the newline character `\n`
|
||||
|
||||
```js
|
||||
assert(/FirstLine\n/.test(myStr));
|
||||
```
|
||||
|
||||
`myStr`应该包含制表符`\t`并且制表符要在换行符后面。
|
||||
`myStr` should contain a tab character `\t` which follows a newline character
|
||||
|
||||
```js
|
||||
assert(/\n\t/.test(myStr));
|
||||
```
|
||||
|
||||
`SecondLine`前面应该是反斜杠`\\`。
|
||||
`SecondLine` should be preceded by the backslash character <code>\\</code>
|
||||
|
||||
```js
|
||||
assert(/\SecondLine/.test(myStr));
|
||||
assert(/\\SecondLine/.test(myStr));
|
||||
```
|
||||
|
||||
`SecondLine`和`ThirdLine`之间应该是换行符。
|
||||
There should be a newline character between `SecondLine` and `ThirdLine`
|
||||
|
||||
```js
|
||||
assert(/SecondLine\nThirdLine/.test(myStr));
|
||||
```
|
||||
|
||||
`myStr` 应该只包含介绍里面展示的字符串。
|
||||
`myStr` should only contain characters shown in the instructions
|
||||
|
||||
```js
|
||||
assert(myStr === 'FirstLine\n\t\\SecondLine\nThirdLine');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b5
|
||||
title: 转义字符串中的引号
|
||||
title: Escaping Literal Quotes in Strings
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QvgSr'
|
||||
forumTopicId: 17568
|
||||
@ -9,34 +9,34 @@ dashedName: escaping-literal-quotes-in-strings
|
||||
|
||||
# --description--
|
||||
|
||||
定义一个字符串必须要用单引号或双引号来包裹它。那么当你的字符串里面包含:`"`或者`'`时该怎么办呢?
|
||||
When you are defining a string you must start and end with a single or double quote. What happens when you need a literal quote: `"` or `'` inside of your string?
|
||||
|
||||
在 JavaScript 中,你可以通过在引号前面使用<dfn>反斜杠</dfn>(`\`)来转义引号。
|
||||
In JavaScript, you can <dfn>escape</dfn> a quote from considering it as an end of string quote by placing a <dfn>backslash</dfn> (<code>\\</code>) in front of the quote.
|
||||
|
||||
`var sampleStr = "Alan said, \"Peter is learning JavaScript\".";`
|
||||
|
||||
有了转义符号,JavaScript 就知道这个单引号或双引号并不是字符串的结尾,而是字符串内的字符。所以,上面的字符串打印到控制台的结果为:
|
||||
This signals to JavaScript that the following quote is not the end of the string, but should instead appear inside the string. So if you were to print this to the console, you would get:
|
||||
|
||||
`Alan said, "Peter is learning JavaScript".`
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用<dfn>反斜杠</dfn>将一个字符串赋值给变量`myStr`,打印到控制台,输出为:
|
||||
Use <dfn>backslashes</dfn> to assign a string to the `myStr` variable so that if you were to print it to the console, you would see:
|
||||
|
||||
`I am a "double quoted" string inside "double quotes".`
|
||||
|
||||
# --hints--
|
||||
|
||||
你的代码中应该包含两个双引号 (`"`) 以及四个转义的双引 (`\"`)。
|
||||
You should use two double quotes (`"`) and four escaped double quotes (`\"`).
|
||||
|
||||
```js
|
||||
assert(code.match(/\\"/g).length === 4 && code.match(/[^\\]"/g).length === 2);
|
||||
```
|
||||
|
||||
变量 myStr 应该包含字符串`I am a "double quoted" string inside "double quotes".`。
|
||||
Variable myStr should contain the string: `I am a "double quoted" string inside "double quotes".`
|
||||
|
||||
```js
|
||||
assert(myStr === 'I am a "double quoted" string inside "double quotes".');
|
||||
assert(/I am a "double quoted" string inside "double quotes(\."|"\.)$/.test(myStr));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7123c9c448eddfaeb5bdef
|
||||
title: 查找字符串的长度
|
||||
title: Find the Length of a String
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cvmqEAd'
|
||||
forumTopicId: 18182
|
||||
@ -9,19 +9,19 @@ dashedName: find-the-length-of-a-string
|
||||
|
||||
# --description--
|
||||
|
||||
你可以通过在字符串变量或字符串后面写上`.length`来获得字符串变量值的长度。
|
||||
You can find the length of a `String` value by writing `.length` after the string variable or string literal.
|
||||
|
||||
`"Alan Peter".length; // 10`
|
||||
|
||||
例如,我们创建了一个变量`var firstName = "Charles"`,我们就可以通过使用`firstName.length`来获得`"Charles"`字符串的长度。
|
||||
For example, if we created a variable `var firstName = "Charles"`, we could find out how long the string `"Charles"` is by using the `firstName.length` property.
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用`.length`属性来获得变量`lastName`的长度,并把它赋值给变量`lastNameLength`。
|
||||
Use the `.length` property to count the number of characters in the `lastName` variable and assign it to `lastNameLength`.
|
||||
|
||||
# --hints--
|
||||
|
||||
不能改变 `// Setup` 部分声明的变量。
|
||||
You should not change the variable declarations in the `// Setup` section.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -30,13 +30,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`lastNameLength`应该等于 8。
|
||||
`lastNameLength` should be equal to eight.
|
||||
|
||||
```js
|
||||
assert(typeof lastNameLength !== 'undefined' && lastNameLength === 8);
|
||||
```
|
||||
|
||||
你应该使用 `.length` 获取 `lastName` 的长度,像这样 `lastName.length`。
|
||||
You should be getting the length of `lastName` by using `.length` like this: `lastName.length`.
|
||||
|
||||
```js
|
||||
assert(code.match(/=\s*lastName\.length/g) && !code.match(/lastName\s*=\s*8/));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ae
|
||||
title: 求余运算
|
||||
title: Finding a Remainder in JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWP24Ub'
|
||||
forumTopicId: 18184
|
||||
@ -9,42 +9,42 @@ dashedName: finding-a-remainder-in-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>remainder</dfn>求余运算符`%`返回两个数相除得到的余数
|
||||
The <dfn>remainder</dfn> operator `%` gives the remainder of the division of two numbers.
|
||||
|
||||
**示例**
|
||||
**Example**
|
||||
|
||||
<blockquote>5 % 2 = 1 因为<br>Math.floor(5 / 2) = 2 (商)<br>2 * 2 = 4<br>5 - 4 = 1 (余数)</blockquote>
|
||||
<blockquote>5 % 2 = 1 because<br>Math.floor(5 / 2) = 2 (Quotient)<br>2 * 2 = 4<br>5 - 4 = 1 (Remainder)</blockquote>
|
||||
|
||||
**用法**
|
||||
在数学中,判断一个数是奇数还是偶数,只需要判断这个数除以 2 得到的余数是 0 还是 1。
|
||||
**Usage**
|
||||
In mathematics, a number can be checked to be even or odd by checking the remainder of the division of the number by `2`.
|
||||
|
||||
<blockquote>17 % 2 = 1(17 是奇数)<br>48 % 2 = 0(48 是偶数)</blockquote>
|
||||
<blockquote>17 % 2 = 1 (17 is Odd)<br>48 % 2 = 0 (48 is Even)</blockquote>
|
||||
|
||||
**提示**
|
||||
余数运算符(<dfn>remainder</dfn>)有时被错误地称为“模数”运算符。它与模数非常相似,但不能用于负数的运算。\*\*\*\*
|
||||
**Note**
|
||||
The <dfn>remainder</dfn> operator is sometimes incorrectly referred to as the "modulus" operator. It is very similar to modulus, but does not work properly with negative numbers.
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用`%`运算符,计算 11 除以 3 的余数,并把余数赋给变量 remainder。
|
||||
Set `remainder` equal to the remainder of `11` divided by `3` using the <dfn>remainder</dfn> (`%`) operator.
|
||||
|
||||
# --hints--
|
||||
|
||||
变量`remainder`应该被初始化。
|
||||
The variable `remainder` should be initialized
|
||||
|
||||
```js
|
||||
assert(/var\s+?remainder/.test(code));
|
||||
```
|
||||
|
||||
`remainder`的值应该等于`2`。
|
||||
The value of `remainder` should be `2`
|
||||
|
||||
```js
|
||||
assert(remainder === 2);
|
||||
```
|
||||
|
||||
你应该使用`%`运算符。
|
||||
You should use the `%` operator
|
||||
|
||||
```js
|
||||
assert(/\s+?remainder\s*?=\s*?.*%.*;/.test(code));
|
||||
assert(/\s+?remainder\s*?=\s*?.*%.*;?/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb9bdef
|
||||
title: 使用 JavaScript 生成随机分数
|
||||
title: Generate Random Fractions with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cyWJJs3'
|
||||
forumTopicId: 18185
|
||||
@ -9,32 +9,32 @@ dashedName: generate-random-fractions-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
随机数非常适合用来创建随机行为。
|
||||
Random numbers are useful for creating random behavior.
|
||||
|
||||
`Math.random()`用来生成一个在`0`(包括 0)到`1`(不包括 1)之间的随机小数,因此`Math.random()`可能返回 0 但绝不会返回 1。
|
||||
JavaScript has a `Math.random()` function that generates a random decimal number between `0` (inclusive) and not quite up to `1` (exclusive). Thus `Math.random()` can return a `0` but never quite return a `1`
|
||||
|
||||
**提示**
|
||||
[使用赋值运算符存储值](storing-values-with-the-assignment-operator)这一节讲过,所有函数调用将在`return`执行之前解析,因此我们可以返回`Math.random()`函数的值。
|
||||
**Note**
|
||||
Like [Storing Values with the Equal Operator](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator), all function calls will be resolved before the `return` executes, so we can `return` the value of the `Math.random()` function.
|
||||
|
||||
# --instructions--
|
||||
|
||||
更改`randomFraction`使其返回一个随机数而不是`0`。
|
||||
Change `randomFraction` to return a random number instead of returning `0`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`randomFraction`应该返回一个随机数。
|
||||
`randomFraction` should return a random number.
|
||||
|
||||
```js
|
||||
assert(typeof randomFraction() === 'number');
|
||||
```
|
||||
|
||||
`randomFraction`应该返回一个小数。
|
||||
The number returned by `randomFraction` should be a decimal.
|
||||
|
||||
```js
|
||||
assert((randomFraction() + '').match(/\./g));
|
||||
```
|
||||
|
||||
需要使用`Math.random`生成随机的小数。
|
||||
You should be using `Math.random` to generate the random decimal number.
|
||||
|
||||
```js
|
||||
assert(code.match(/Math\.random/g).length >= 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c12feddfaeb1bdef
|
||||
title: 使用 JavaScript 生成随机整数
|
||||
title: Generate Random Whole Numbers with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRn6bfr'
|
||||
forumTopicId: 18186
|
||||
@ -9,25 +9,25 @@ dashedName: generate-random-whole-numbers-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
生成随机小数很棒,但随机数更有用的地方在于生成随机整数。
|
||||
It's great that we can generate random decimal numbers, but it's even more useful if we use it to generate random whole numbers.
|
||||
|
||||
<ol><li>用<code>Math.random()</code>生成一个随机小数。</li><li>把这个随机小数乘以<code>20</code>。</li><li>用<code>Math.floor()</code>向下取整 获得它最近的整数。</li></ol>
|
||||
<ol><li>Use <code>Math.random()</code> to generate a random decimal.</li><li>Multiply that random decimal by <code>20</code>.</li><li>Use another function, <code>Math.floor()</code> to round the number down to its nearest whole number.</li></ol>
|
||||
|
||||
记住`Math.random()`永远不会返回`1`。同时因为我们是在用`Math.floor()`向下取整,所以最终我们获得的结果不可能有`20`。这确保了我们获得了一个在0到19之间的整数。
|
||||
Remember that `Math.random()` can never quite return a `1` and, because we're rounding down, it's impossible to actually get `20`. This technique will give us a whole number between `0` and `19`.
|
||||
|
||||
把操作连缀起来,代码类似于下面:
|
||||
Putting everything together, this is what our code looks like:
|
||||
|
||||
`Math.floor(Math.random() * 20);`
|
||||
|
||||
我们先调用`Math.random()`,把它的结果乘以20,然后把上一步的结果传给`Math.floor()`,最终通过向下取整获得最近的整数。
|
||||
We are calling `Math.random()`, multiplying the result by 20, then passing the value to `Math.floor()` function to round the value down to the nearest whole number.
|
||||
|
||||
# --instructions--
|
||||
|
||||
生成一个`0`到`9`之间的随机整数。
|
||||
Use this technique to generate and return a random whole number between `0` and `9`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myFunction`的结果应该是一个整数。
|
||||
The result of `randomWholeNum` should be a whole number.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -39,13 +39,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
需要使用`Math.random`生成随机数字。
|
||||
You should use `Math.random` to generate a random number.
|
||||
|
||||
```js
|
||||
assert(code.match(/Math.random/g).length > 1);
|
||||
assert(code.match(/Math.random/g).length >= 1);
|
||||
```
|
||||
|
||||
你应该将`Math.random`的结果乘以 10 来生成 0 到 9 之间的随机数。
|
||||
You should have multiplied the result of `Math.random` by 10 to make it a number that is between zero and nine.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -54,10 +54,10 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
你需要使用`Math.floor`移除数字中的小数部分。
|
||||
You should use `Math.floor` to remove the decimal part of the number.
|
||||
|
||||
```js
|
||||
assert(code.match(/Math.floor/g).length > 1);
|
||||
assert(code.match(/Math.floor/g).length >= 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c12feddfaeb2bdef
|
||||
title: 生成某个范围内的随机整数
|
||||
title: Generate Random Whole Numbers within a Range
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cm83yu6'
|
||||
forumTopicId: 18187
|
||||
@ -9,39 +9,39 @@ dashedName: generate-random-whole-numbers-within-a-range
|
||||
|
||||
# --description--
|
||||
|
||||
我们之前生成的随机数是在0到某个数之间,现在我们要生成的随机数是在两个指定的数之间。
|
||||
Instead of generating a random whole number between zero and a given number like we did before, we can generate a random whole number that falls within a range of two specific numbers.
|
||||
|
||||
我们需要定义一个最小值和一个最大值。
|
||||
To do this, we'll define a minimum number `min` and a maximum number `max`.
|
||||
|
||||
下面是我们将要使用的方法,仔细看看并尝试理解这行代码到底在干嘛:
|
||||
Here's the formula we'll use. Take a moment to read it and try to understand what this code is doing:
|
||||
|
||||
`Math.floor(Math.random() * (max - min + 1)) + min`
|
||||
|
||||
# --instructions--
|
||||
|
||||
创建一个叫`randomRange`的函数,参数为 myMin 和 myMax,返回一个在`myMin`(包括 myMin)和`myMax`(包括 myMax)之间的随机数。
|
||||
Create a function called `randomRange` that takes a range `myMin` and `myMax` and returns a random whole number that's greater than or equal to `myMin`, and is less than or equal to `myMax`, inclusive.
|
||||
|
||||
# --hints--
|
||||
|
||||
`randomRange`返回的随机数应该大于或等于`myMin`。
|
||||
The lowest random number that can be generated by `randomRange` should be equal to your minimum number, `myMin`.
|
||||
|
||||
```js
|
||||
assert(calcMin === 5);
|
||||
```
|
||||
|
||||
`randomRange`返回的随机数应该小于或等于`myMax`。
|
||||
The highest random number that can be generated by `randomRange` should be equal to your maximum number, `myMax`.
|
||||
|
||||
```js
|
||||
assert(calcMax === 15);
|
||||
```
|
||||
|
||||
`randomRange`应该返回一个随机整数, 而不是小数。
|
||||
The random number generated by `randomRange` should be an integer, not a decimal.
|
||||
|
||||
```js
|
||||
assert(randomRange(0, 1) % 1 === 0);
|
||||
```
|
||||
|
||||
`randomRange`应该使用`myMax`和`myMin`, 并且返回两者之间的随机数。
|
||||
`randomRange` should use both `myMax` and `myMin`, and return a random number in your range.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244be
|
||||
title: 全局作用域和函数
|
||||
title: Global Scope and Functions
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cQM7mCN'
|
||||
forumTopicId: 18193
|
||||
@ -9,37 +9,37 @@ dashedName: global-scope-and-functions
|
||||
|
||||
# --description--
|
||||
|
||||
在 JavaScript 中,<dfn>作用域</dfn>涉及到变量的作用范围。在函数外定义的变量具有 <dfn>全局</dfn> 作用域。这意味着,具有全局作用域的变量可以在代码的任何地方被调用。
|
||||
In JavaScript, <dfn>scope</dfn> refers to the visibility of variables. Variables which are defined outside of a function block have <dfn>Global</dfn> scope. This means, they can be seen everywhere in your JavaScript code.
|
||||
|
||||
这些没有使用`var`关键字定义的变量,会被自动创建在全局作用域中,形成全局变量。当在代码其他地方无意间定义了一个变量,刚好变量名与全局变量相同,这时会产生意想不到的后果。因此你应该总是使用var关键字来声明你的变量。
|
||||
Variables which are used without the `var` keyword are automatically created in the `global` scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with `var`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
在函数外声明一个`全局`变量`myGlobal`,并给它一个初始值`10`
|
||||
Using `var`, declare a global variable named `myGlobal` outside of any function. Initialize it with a value of `10`.
|
||||
|
||||
在函数`fun1`的内部,**不**使用`var`关键字来声明`oopsGlobal`,并赋值为`5`。
|
||||
Inside function `fun1`, assign `5` to `oopsGlobal` ***without*** using the `var` keyword.
|
||||
|
||||
# --hints--
|
||||
|
||||
应定义`myGlobal`。
|
||||
`myGlobal` should be defined
|
||||
|
||||
```js
|
||||
assert(typeof myGlobal != 'undefined');
|
||||
```
|
||||
|
||||
`myGlobal`的值应为`10`。
|
||||
`myGlobal` should have a value of `10`
|
||||
|
||||
```js
|
||||
assert(myGlobal === 10);
|
||||
```
|
||||
|
||||
应使用`var`关键字定义`myGlobal`。
|
||||
`myGlobal` should be declared using the `var` keyword
|
||||
|
||||
```js
|
||||
assert(/var\s+myGlobal/.test(code));
|
||||
```
|
||||
|
||||
`oopsGlobal`应为全局变量且值为`5`。
|
||||
`oopsGlobal` should be a global variable and have a value of `5`
|
||||
|
||||
```js
|
||||
assert(typeof oopsGlobal != 'undefined' && oopsGlobal === 5);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c0
|
||||
title: 函数中的全局作用域和局部作用域
|
||||
title: Global vs. Local Scope in Functions
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QwKH2'
|
||||
forumTopicId: 18194
|
||||
@ -9,9 +9,9 @@ dashedName: global-vs--local-scope-in-functions
|
||||
|
||||
# --description--
|
||||
|
||||
一个程序中有可能具有相同名称的<dfn>局部</dfn>变量 和<dfn>全局</dfn>变量。在这种情况下,`局部`变量将会优先于`全局`变量。
|
||||
It is possible to have both <dfn>local</dfn> and <dfn>global</dfn> variables with the same name. When you do this, the `local` variable takes precedence over the `global` variable.
|
||||
|
||||
下面为例:
|
||||
In this example:
|
||||
|
||||
```js
|
||||
var someVar = "Hat";
|
||||
@ -21,27 +21,27 @@ function myFun() {
|
||||
}
|
||||
```
|
||||
|
||||
函数`myFun`将会返回`"Head"`,因为`局部变量`优先级更高。
|
||||
The function `myFun` will return `"Head"` because the `local` version of the variable is present.
|
||||
|
||||
# --instructions--
|
||||
|
||||
给`myOutfit`添加一个局部变量来覆盖`outerWear`的值为`"sweater"`。
|
||||
Add a local variable to `myOutfit` function to override the value of `outerWear` with `"sweater"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
不要修改全局变量`outerWear`的值。
|
||||
You should not change the value of the global `outerWear`.
|
||||
|
||||
```js
|
||||
assert(outerWear === 'T-Shirt');
|
||||
```
|
||||
|
||||
`myOutfit`应该返回`"sweater"`。
|
||||
`myOutfit` should return `"sweater"`.
|
||||
|
||||
```js
|
||||
assert(myOutfit() === 'sweater');
|
||||
```
|
||||
|
||||
不要修改`return`语句。
|
||||
You should not change the return statement.
|
||||
|
||||
```js
|
||||
assert(/return outerWear/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5664820f61c48e80c9fa476c
|
||||
title: 高尔夫代码
|
||||
title: Golf Code
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9ykNUR'
|
||||
forumTopicId: 18195
|
||||
@ -9,77 +9,77 @@ dashedName: golf-code
|
||||
|
||||
# --description--
|
||||
|
||||
在高尔夫[golf](https://en.wikipedia.org/wiki/Golf)游戏中,每个洞都有自己的标准杆数`par`,代表着距离。根据你把球打进洞所挥杆的次数`strokes`,可以计算出你的高尔夫水平。
|
||||
In the game of [golf](https://en.wikipedia.org/wiki/Golf) each hole has a `par` meaning the average number of `strokes` a golfer is expected to make in order to sink the ball in a hole to complete the play. Depending on how far above or below `par` your `strokes` are, there is a different nickname.
|
||||
|
||||
函数将会传送 2 个参数,分别是标准杆数`par`和挥杆次数`strokes`,根据下面的表格返回正确的水平段位。
|
||||
Your function will be passed `par` and `strokes` arguments. Return the correct string according to this table which lists the strokes in order of priority; top (highest) to bottom (lowest):
|
||||
|
||||
<table class='table table-striped'><thead><tr><th>Strokes</th><th>Return</th></tr></thead><tbody><tr><td>1</td><td>"Hole-in-one!"</td></tr><tr><td><= par - 2</td><td>"Eagle"</td></tr><tr><td>par - 1</td><td>"Birdie"</td></tr><tr><td>par</td><td>"Par"</td></tr><tr><td>par + 1</td><td>"Bogey"</td></tr><tr><td>par + 2</td><td>"Double Bogey"</td></tr><tr><td>>= par + 3</td><td>"Go Home!"</td></tr></tbody></table>
|
||||
|
||||
`par`和`strokes`必须是数字而且是正数。
|
||||
`par` and `strokes` will always be numeric and positive. We have added an array of all the names for your convenience.
|
||||
|
||||
# --hints--
|
||||
|
||||
`golfScore(4, 1)`应该返回 "Hole-in-one!"。
|
||||
`golfScore(4, 1)` should return "Hole-in-one!"
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 1) === 'Hole-in-one!');
|
||||
```
|
||||
|
||||
`golfScore(4, 2)`应该返回 "Eagle"。
|
||||
`golfScore(4, 2)` should return "Eagle"
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 2) === 'Eagle');
|
||||
```
|
||||
|
||||
`golfScore(5, 2)`应该返回 "Eagle"。
|
||||
`golfScore(5, 2)` should return "Eagle"
|
||||
|
||||
```js
|
||||
assert(golfScore(5, 2) === 'Eagle');
|
||||
```
|
||||
|
||||
`golfScore(4, 3)`应该返回 "Birdie"。
|
||||
`golfScore(4, 3)` should return "Birdie"
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 3) === 'Birdie');
|
||||
```
|
||||
|
||||
`golfScore(4, 4)`应该返回 "Par"。
|
||||
`golfScore(4, 4)` should return "Par"
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 4) === 'Par');
|
||||
```
|
||||
|
||||
`golfScore(1, 1)`应该返回 "Hole-in-one!"。
|
||||
`golfScore(1, 1)` should return "Hole-in-one!"
|
||||
|
||||
```js
|
||||
assert(golfScore(1, 1) === 'Hole-in-one!');
|
||||
```
|
||||
|
||||
`golfScore(5, 5)`应该返回 "Par"。
|
||||
`golfScore(5, 5)` should return "Par"
|
||||
|
||||
```js
|
||||
assert(golfScore(5, 5) === 'Par');
|
||||
```
|
||||
|
||||
`golfScore(4, 5)`应该返回 "Bogey"。
|
||||
`golfScore(4, 5)` should return "Bogey"
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 5) === 'Bogey');
|
||||
```
|
||||
|
||||
`golfScore(4, 6)`应该返回 "Double Bogey"。
|
||||
`golfScore(4, 6)` should return "Double Bogey"
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 6) === 'Double Bogey');
|
||||
```
|
||||
|
||||
`golfScore(4, 7)`应该返回 "Go Home!"。
|
||||
`golfScore(4, 7)` should return "Go Home!"
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 7) === 'Go Home!');
|
||||
```
|
||||
|
||||
`golfScore(5, 9)`应该返回 "Go Home!"。
|
||||
`golfScore(5, 9)` should return "Go Home!"
|
||||
|
||||
```js
|
||||
assert(golfScore(5, 9) === 'Go Home!');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ac
|
||||
title: 数字递增
|
||||
title: Increment a Number with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ca8GLT9'
|
||||
forumTopicId: 18201
|
||||
@ -9,45 +9,44 @@ dashedName: increment-a-number-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
使用`++`,我们可以很容易地对变量进行自增或者`+1`运算。
|
||||
You can easily <dfn>increment</dfn> or add one to a variable with the `++` operator.
|
||||
|
||||
`i++;`
|
||||
|
||||
等效于
|
||||
is the equivalent of
|
||||
|
||||
`i = i + 1;`
|
||||
|
||||
**注意**
|
||||
`i++;`这种写法,省去了书写`=`符号的必要。
|
||||
**Note**
|
||||
The entire line becomes `i++;`, eliminating the need for the equal sign.
|
||||
|
||||
# --instructions--
|
||||
|
||||
重写代码,使用`++`来对变量`myVar`进行自增操作。
|
||||
|
||||
**提示**
|
||||
了解更多关于`++`运算符[Arithmetic operators - Increment (++)](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#%E9%80%92%E5%A2%9E_()).
|
||||
Change the code to use the `++` operator on `myVar`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myVar`应该等于`88`。
|
||||
`myVar` should equal `88`.
|
||||
|
||||
```js
|
||||
assert(myVar === 88);
|
||||
```
|
||||
|
||||
`myVar = myVar + 1;`语句应该被修改。
|
||||
You should not use the assignment operator.
|
||||
|
||||
```js
|
||||
assert(/var\s*myVar\s*=\s*87;\s*\/*.*\s*myVar\+\+;/.test(code));
|
||||
assert(
|
||||
/var\s*myVar\s*=\s*87;\s*\/*.*\s*([+]{2}\s*myVar|myVar\s*[+]{2});/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
使用`++`运算符。
|
||||
You should use the `++` operator.
|
||||
|
||||
```js
|
||||
assert(/[+]{2}\s*myVar|myVar\s*[+]{2}/.test(code));
|
||||
```
|
||||
|
||||
不要修改注释上方的代码。
|
||||
You should not change code above the specified comment.
|
||||
|
||||
```js
|
||||
assert(/var myVar = 87;/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244a9
|
||||
title: 使用赋值运算符初始化变量
|
||||
title: Initializing Variables with the Assignment Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWJ4Bfb'
|
||||
forumTopicId: 301171
|
||||
@ -9,22 +9,22 @@ dashedName: initializing-variables-with-the-assignment-operator
|
||||
|
||||
# --description--
|
||||
|
||||
通常在声明变量的时候会给变量<dfn>初始化</dfn>一个初始值。
|
||||
It is common to <dfn>initialize</dfn> a variable to an initial value in the same line as it is declared.
|
||||
|
||||
`var myVar = 0;`
|
||||
|
||||
创建一个名为`myVar`的变量并指定一个初始值`0`。
|
||||
Creates a new variable called `myVar` and assigns it an initial value of `0`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
通过关键字`var`定义一个变量`a`并且给它一个初始值`9`。
|
||||
Define a variable `a` with `var` and initialize it to a value of `9`.
|
||||
|
||||
# --hints--
|
||||
|
||||
你需要初始化`a`的值为`9`。
|
||||
You should initialize `a` to a value of `9`.
|
||||
|
||||
```js
|
||||
assert(/var\s+a\s*=\s*9\s*/.test(code));
|
||||
assert(/var\s+a\s*=\s*9(\s*;?\s*)$/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@ -36,7 +36,6 @@ if(typeof a !== 'undefined') {(function(a){return "a = " + a;})(a);} else { (fun
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
```
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244db
|
||||
title: 介绍 else if 语句
|
||||
title: Introducing Else If Statements
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/caeJ2hm'
|
||||
forumTopicId: 18206
|
||||
@ -9,7 +9,7 @@ dashedName: introducing-else-if-statements
|
||||
|
||||
# --description--
|
||||
|
||||
如果你有多个条件语句,你可以通过`else if`语句把`if`语句链起来。
|
||||
If you have multiple conditions that need to be addressed, you can chain `if` statements together with `else if` statements.
|
||||
|
||||
```js
|
||||
if (num > 15) {
|
||||
@ -23,53 +23,57 @@ if (num > 15) {
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用`if else`实现同样的效果。
|
||||
Convert the logic to use `else if` statements.
|
||||
|
||||
# --hints--
|
||||
|
||||
你应该至少有两个`else`表达式。
|
||||
You should have at least two `else` statements
|
||||
|
||||
```js
|
||||
assert(code.match(/else/g).length > 1);
|
||||
```
|
||||
|
||||
你应该至少有两个`if`表达式。
|
||||
You should have at least two `if` statements
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length > 1);
|
||||
```
|
||||
|
||||
`testElseIf(0)`应该返回 "Smaller than 5"。
|
||||
You should have closing and opening curly braces for each `if else` code block.
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(
|
||||
/if\s*\((.+)\)\s*\{[\s\S]+\}\s*else\s+if\s*\((.+)\)\s*\{[\s\S]+\}\s*else\s*\{[\s\S]+\s*\}/
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
`testElseIf(0)` should return "Smaller than 5"
|
||||
|
||||
```js
|
||||
assert(testElseIf(0) === 'Smaller than 5');
|
||||
```
|
||||
|
||||
`testElseIf(5)`应该返回 "Between 5 and 10"。
|
||||
`testElseIf(5)` should return "Between 5 and 10"
|
||||
|
||||
```js
|
||||
assert(testElseIf(5) === 'Between 5 and 10');
|
||||
```
|
||||
|
||||
`testElseIf(7)`应该返回 "Between 5 and 10"。
|
||||
`testElseIf(7)` should return "Between 5 and 10"
|
||||
|
||||
```js
|
||||
assert(testElseIf(7) === 'Between 5 and 10');
|
||||
```
|
||||
|
||||
`testElseIf(10)`应该返回 "Between 5 and 10"。
|
||||
`testElseIf(10)` should return "Between 5 and 10"
|
||||
|
||||
```js
|
||||
assert(testElseIf(10) === 'Between 5 and 10');
|
||||
```
|
||||
|
||||
`testElseIf(12)`应该返回 "Greater than 10"。
|
||||
|
||||
```js
|
||||
assert(testElseIf(12) === 'Greater than 10');
|
||||
```
|
||||
|
||||
`testElseIf(12)` 应该返回 "Greater than 10"。
|
||||
`testElseIf(12)` should return "Greater than 10"
|
||||
|
||||
```js
|
||||
assert(testElseIf(12) === 'Greater than 10');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244da
|
||||
title: 介绍 else 语句
|
||||
title: Introducing Else Statements
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cek4Efq'
|
||||
forumTopicId: 18207
|
||||
@ -9,7 +9,7 @@ dashedName: introducing-else-statements
|
||||
|
||||
# --description--
|
||||
|
||||
当`if`语句的条件为真,大括号里的代码执行,那如果条件为假呢?正常情况下什么也不会发生。使用else语句,可以执行当条件为假时相应的代码。
|
||||
When a condition for an `if` statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen. With an `else` statement, an alternate block of code can be executed.
|
||||
|
||||
```js
|
||||
if (num > 10) {
|
||||
@ -21,47 +21,47 @@ if (num > 10) {
|
||||
|
||||
# --instructions--
|
||||
|
||||
请把多个`if`语句合并为一个`if/else`语句。
|
||||
Combine the `if` statements into a single `if/else` statement.
|
||||
|
||||
# --hints--
|
||||
|
||||
你应该只有一个`if`表达式。
|
||||
You should only have one `if` statement in the editor
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length === 1);
|
||||
```
|
||||
|
||||
你应该使用一个`else`表达式。
|
||||
You should use an `else` statement
|
||||
|
||||
```js
|
||||
assert(/else/g.test(code));
|
||||
```
|
||||
|
||||
`testElse(4)`应该返回 "5 or Smaller"。
|
||||
`testElse(4)` should return "5 or Smaller"
|
||||
|
||||
```js
|
||||
assert(testElse(4) === '5 or Smaller');
|
||||
```
|
||||
|
||||
`testElse(5)`应该返回 "5 or Smaller"。
|
||||
`testElse(5)` should return "5 or Smaller"
|
||||
|
||||
```js
|
||||
assert(testElse(5) === '5 or Smaller');
|
||||
```
|
||||
|
||||
`testElse(6)`应该返回 "Bigger than 5"。
|
||||
`testElse(6)` should return "Bigger than 5"
|
||||
|
||||
```js
|
||||
assert(testElse(6) === 'Bigger than 5');
|
||||
```
|
||||
|
||||
`testElse(10)`应该返回 "Bigger than 5"。
|
||||
`testElse(10)` should return "Bigger than 5".
|
||||
|
||||
```js
|
||||
assert(testElse(10) === 'Bigger than 5');
|
||||
```
|
||||
|
||||
不要修改上面和下面的代码。
|
||||
You should not change the code above or below the specified comments.
|
||||
|
||||
```js
|
||||
assert(/var result = "";/.test(code) && /return result;/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56104e9e514f539506016a5c
|
||||
title: 使用 For 循环遍历数组的奇数
|
||||
title: Iterate Odd Numbers With a For Loop
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cm8n7T9'
|
||||
forumTopicId: 18212
|
||||
@ -9,11 +9,9 @@ dashedName: iterate-odd-numbers-with-a-for-loop
|
||||
|
||||
# --description--
|
||||
|
||||
for循环可以按照我们指定的顺序来迭代,通过更改我们的`计数器`,我们可以按照偶数顺序来迭代。
|
||||
For loops don't have to iterate one at a time. By changing our `final-expression`, we can count by even numbers.
|
||||
|
||||
初始化`i = 0`,当`i < 10`的时候继续循环。
|
||||
|
||||
`i += 2`让`i`每次循环之后增加2。
|
||||
We'll start at `i = 0` and loop while `i < 10`. We'll increment `i` by 2 each loop with `i += 2`.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
@ -22,21 +20,21 @@ for (var i = 0; i < 10; i += 2) {
|
||||
}
|
||||
```
|
||||
|
||||
循环结束后,`ourArray`的值为`[0,2,4,6,8]`。 改变`计数器`,这样我们可以用奇数来数。
|
||||
`ourArray` will now contain `[0,2,4,6,8]`. Let's change our `initialization` so we can count by odd numbers.
|
||||
|
||||
# --instructions--
|
||||
|
||||
写一个`for`循环,把从 1 到 9 的奇数添加到`myArray`。
|
||||
Push the odd numbers from 1 through 9 to `myArray` using a `for` loop.
|
||||
|
||||
# --hints--
|
||||
|
||||
你应该使用`for`循环。
|
||||
You should be using a `for` loop for this.
|
||||
|
||||
```js
|
||||
assert(code.match(/for\s*\(/g).length > 1);
|
||||
assert(/for\s*\([^)]+?\)/.test(code));
|
||||
```
|
||||
|
||||
`myArray`应该等于`[1,3,5,7,9]`。
|
||||
`myArray` should equal `[1,3,5,7,9]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [1, 3, 5, 7, 9]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5675e877dbd60be8ad28edc6
|
||||
title: 使用 For 循环遍历数组
|
||||
title: Iterate Through an Array with a For Loop
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/caeR3HB'
|
||||
forumTopicId: 18216
|
||||
@ -9,7 +9,7 @@ dashedName: iterate-through-an-array-with-a-for-loop
|
||||
|
||||
# --description--
|
||||
|
||||
迭代输出一个数组的每个元素是 JavaScript 中的常见需求,`for`循环可以做到这一点。下面的代码将输出数组 `arr`的每个元素到控制台:
|
||||
A common task in JavaScript is to iterate through the contents of an array. One way to do that is with a `for` loop. This code will output each element of the array `arr` to the console:
|
||||
|
||||
```js
|
||||
var arr = [10, 9, 8, 7, 6];
|
||||
@ -18,36 +18,36 @@ for (var i = 0; i < arr.length; i++) {
|
||||
}
|
||||
```
|
||||
|
||||
记住数组的索引从零开始的,这意味着数组的最后一个元素的下标是:数组的长度 -1。我们这个循环的 <dfn>条件</dfn>是`i < arr.length`,当`i`的值为 长度 -1 的时候循环就停止了。在这个例子中,最后一个循环是 i === 4,也就是说,当i的值等于arr.length时,结果输出 6。
|
||||
Remember that arrays have zero-based indexing, which means the last index of the array is `length - 1`. Our condition for this loop is `i < arr.length`, which stops the loop when `i` is equal to `length`. In this case the last iteration is `i === 4` i.e. when `i` becomes equal to `arr.length` and outputs `6` to the console.
|
||||
|
||||
# --instructions--
|
||||
|
||||
声明并初始化一个变量`total`为`0`。使用`for`循环,使得`total`的值为`myArr`的数组中的每个元素的值的总和。
|
||||
Declare and initialize a variable `total` to `0`. Use a `for` loop to add the value of each element of the `myArr` array to `total`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`total`应该被声明, 并且初始化值为 0。
|
||||
`total` should be declared and initialized to 0.
|
||||
|
||||
```js
|
||||
assert(code.match(/var.*?total\s*=\s*0.*?;/));
|
||||
assert(code.match(/(var|let|const)\s*?total\s*=\s*0.*?;?/));
|
||||
```
|
||||
|
||||
`total`应该等于 20。
|
||||
`total` should equal 20.
|
||||
|
||||
```js
|
||||
assert(total === 20);
|
||||
```
|
||||
|
||||
你应该使用`for`循环在`myArr`中遍历。
|
||||
You should use a `for` loop to iterate through `myArr`.
|
||||
|
||||
```js
|
||||
assert(code.match(/for\s*\(/g).length > 1 && code.match(/myArr\s*\[/));
|
||||
assert(/for\s*\(/g.test(code) && /myArr\s*\[/g.test(code));
|
||||
```
|
||||
|
||||
不能直接把`total`设置成 20。
|
||||
You should not attempt to directly assign the value 20 to `total`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/total[\s\+\-]*=\s*(\d(?!\s*[;,])|[1-9])/g));
|
||||
assert(!__helpers.removeWhiteSpace(code).match(/total[=+-]0*[1-9]+/gm));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a2efd662fb457916e1fe604
|
||||
title: do...while 循环
|
||||
title: Iterate with JavaScript Do...While Loops
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDqWGcp'
|
||||
forumTopicId: 301172
|
||||
@ -9,7 +9,7 @@ dashedName: iterate-with-javascript-do---while-loops
|
||||
|
||||
# --description--
|
||||
|
||||
这一节我们将要学习的是`do...while`循环,它会先执行`do`里面的代码,如果`while`表达式为真则重复执行,反之则停止执行。我们来看一个例子。
|
||||
The next type of loop you will learn is called a `do...while` loop. It is called a `do...while` loop because it will first `do` one pass of the code inside the loop no matter what, and then continue to run the loop `while` the specified condition evaluates to `true`.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
@ -20,7 +20,7 @@ do {
|
||||
} while (i < 5);
|
||||
```
|
||||
|
||||
这看起来和其他循环语句差不多,返回的结果是`[0, 1, 2, 3, 4]`,`do...while`与其他循环不同点在于,初始条件为假时的表现,让我们通过实际的例子来看看。 这是一个普通的 while 循环,只要`i < 5`,它就会在循环中运行代码。
|
||||
The example above behaves similar to other types of loops, and the resulting array will look like `[0, 1, 2, 3, 4]`. However, what makes the `do...while` different from other loops is how it behaves when the condition fails on the first check. Let's see this in action: Here is a regular `while` loop that will run the code in the loop as long as `i < 5`:
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
@ -31,7 +31,7 @@ while (i < 5) {
|
||||
}
|
||||
```
|
||||
|
||||
注意,我们首先将`i`的值初始化为 5。执行下一行时,注意到`i`不小于 5,循环内的代码将不会执行。所以`ourArray`最终没有添加任何内容,因此示例中的所有代码执行完时,`ourArray`仍然是`[]`。 现在,看一下`do...while`循环。
|
||||
In this example, we initialize the value of `ourArray` to an empty array and the value of `i` to 5. When we execute the `while` loop, the condition evaluates to `false` because `i` is not less than 5, so we do not execute the code inside the loop. The result is that `ourArray` will end up with no values added to it, and it will still look like `[]` when all of the code in the example above has completed running. Now, take a look at a `do...while` loop:
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
@ -42,30 +42,30 @@ do {
|
||||
} while (i < 5);
|
||||
```
|
||||
|
||||
在这里,和使用 while 循环时一样,我们将`i`的值初始化为 5。执行下一行时,没有检查`i`的值,直接执行花括号内的代码。数组会添加一个元素,并在进行条件检查之前递增`i`。然后,在条件检查时因为`i`等于 6 不符合条件`i < 5`,所以退出循环。最终`ourArray`的值是`[5]`。 本质上,`do...while`循环确保循环内的代码至少运行一次。 让我们通过`do...while`循环将值添加到数组中。
|
||||
In this case, we initialize the value of `i` to 5, just like we did with the `while` loop. When we get to the next line, there is no condition to evaluate, so we go to the code inside the curly braces and execute it. We will add a single element to the array and then increment `i` before we get to the condition check. When we finally evaluate the condition `i < 5` on the last line, we see that `i` is now 6, which fails the conditional check, so we exit the loop and are done. At the end of the above example, the value of `ourArray` is `[5]`. Essentially, a `do...while` loop ensures that the code inside the loop will run at least once. Let's try getting a `do...while` loop to work by pushing values to an array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
将代码中的`while`循环更改为`do...while`循环,实现数字 10 添加到`myArray`中,代码执行完时,`i`等于`11`。
|
||||
Change the `while` loop in the code to a `do...while` loop so the loop will push only the number `10` to `myArray`, and `i` will be equal to `11` when your code has finished running.
|
||||
|
||||
# --hints--
|
||||
|
||||
你应该使用`do...while`循环。
|
||||
You should be using a `do...while` loop for this exercise.
|
||||
|
||||
```js
|
||||
assert(code.match(/do/g));
|
||||
```
|
||||
|
||||
`myArray`应该等于`[10]`。
|
||||
`myArray` should equal `[10]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [10]);
|
||||
```
|
||||
|
||||
`i`应该等于`11`。
|
||||
`i` should equal `11`
|
||||
|
||||
```js
|
||||
assert.deepEqual(i, 11);
|
||||
assert.equal(i, 11);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb5bdef
|
||||
title: for 循环
|
||||
title: Iterate with JavaScript For Loops
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9yNVCe'
|
||||
forumTopicId: 18219
|
||||
@ -9,21 +9,21 @@ dashedName: iterate-with-javascript-for-loops
|
||||
|
||||
# --description--
|
||||
|
||||
你可以使用循环多次执行相同的代码。
|
||||
You can run the same code multiple times by using a loop.
|
||||
|
||||
JavaScript 中最常见的循环就是 “`for循环`”。
|
||||
The most common type of JavaScript loop is called a `for` loop because it runs "for" a specific number of times.
|
||||
|
||||
for循环中的三个表达式用分号隔开:
|
||||
For loops are declared with three optional expressions separated by semicolons:
|
||||
|
||||
`for ([初始化]; [条件判断]; [计数器])`
|
||||
`for ([initialization]; [condition]; [final-expression])`
|
||||
|
||||
`初始化`语句只会在执行循环开始之前执行一次。它通常用于定义和设置你的循环变量。
|
||||
The `initialization` statement is executed one time only before the loop starts. It is typically used to define and setup your loop variable.
|
||||
|
||||
`条件判断`语句会在每一轮循环的开始执行,只要条件判断为`true`就会继续执行循环。当条件为`false`的时候,循环将停止执行。这意味着,如果条件在一开始就为`false`,这个循环将不会执行。
|
||||
The `condition` statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to `true`. When `condition` is `false` at the start of the iteration, the loop will stop executing. This means if `condition` starts as `false`, your loop will never execute.
|
||||
|
||||
`计数器`是在每一轮循环结束时执行,通常用于递增或递减。
|
||||
The `final-expression` is executed at the end of each loop iteration, prior to the next `condition` check and is usually used to increment or decrement your loop counter.
|
||||
|
||||
在下面的例子中,先初始化`i = 0`,条件`i < 5`为真,进入第一次循环,执行大括号里的代码,第一次循环结束。递增`i`的值,条件判断,就这样依次执行下去,直到条件判断为假,整个循环结束。
|
||||
In the following example we initialize with `i = 0` and iterate while our condition `i < 5` is true. We'll increment `i` by `1` in each loop iteration with `i++` as our `final-expression`.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
@ -32,21 +32,21 @@ for (var i = 0; i < 5; i++) {
|
||||
}
|
||||
```
|
||||
|
||||
最终`ourArray`的值为`[0,1,2,3,4]`.
|
||||
`ourArray` will now contain `[0,1,2,3,4]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用`for`循环把从 1 到 5 添加进`myArray`中。
|
||||
Use a `for` loop to work to push the values 1 through 5 onto `myArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
你应该使用`for`循环。
|
||||
You should be using a `for` loop for this.
|
||||
|
||||
```js
|
||||
assert(code.match(/for\s*\(/g).length > 1);
|
||||
assert(/for\s*\([^)]+?\)/.test(code));
|
||||
```
|
||||
|
||||
`myArray`应该等于`[1,2,3,4,5]`。
|
||||
`myArray` should equal `[1,2,3,4,5]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [1, 2, 3, 4, 5]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb1bdef
|
||||
title: while 循环
|
||||
title: Iterate with JavaScript While Loops
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c8QbnCM'
|
||||
forumTopicId: 18220
|
||||
@ -9,9 +9,9 @@ dashedName: iterate-with-javascript-while-loops
|
||||
|
||||
# --description--
|
||||
|
||||
你可以使用循环多次执行相同的代码。
|
||||
You can run the same code multiple times by using a loop.
|
||||
|
||||
我们将学习的第一种类型的循环称为 "`while`" 循环,因为它规定,当 "while" 条件为真,循环才会执行,反之不执行。
|
||||
The first type of loop we will learn is called a `while` loop because it runs "while" a specified condition is true and stops once that condition is no longer true.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
@ -22,26 +22,26 @@ while(i < 5) {
|
||||
}
|
||||
```
|
||||
|
||||
在上面的代码里,`while` 循环执行 5 次把 0 到 4 的数字添加到 `ourArray` 数组里。
|
||||
In the code example above, the `while` loop will execute 5 times and append the numbers 0 through 4 to `ourArray`.
|
||||
|
||||
让我们通过 while 循环将值添加到数组中。
|
||||
Let's try getting a while loop to work by pushing values to an array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
通过一个`while`循环,把从 0 到 4 的值添加到`myArray`中。
|
||||
Add the numbers 5 through 0 (inclusive) in descending order to `myArray` using a `while` loop.
|
||||
|
||||
# --hints--
|
||||
|
||||
你应该使用`while`循环。
|
||||
You should be using a `while` loop for this.
|
||||
|
||||
```js
|
||||
assert(code.match(/while/g));
|
||||
```
|
||||
|
||||
`myArray`应该等于`[0,1,2,3,4]`。
|
||||
`myArray` should equal `[5,4,3,2,1,0]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [0, 1, 2, 3, 4]);
|
||||
assert.deepEqual(myArray, [5, 4, 3, 2, 1, 0]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244bf
|
||||
title: 局部作用域和函数
|
||||
title: Local Scope and Functions
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cd62NhM'
|
||||
forumTopicId: 18227
|
||||
@ -9,9 +9,9 @@ dashedName: local-scope-and-functions
|
||||
|
||||
# --description--
|
||||
|
||||
在一个函数内声明的变量,以及该函数的参数都是局部变量,意味着它们只在该函数内可见。
|
||||
Variables which are declared within a function, as well as the function parameters have <dfn>local</dfn> scope. That means, they are only visible within that function.
|
||||
|
||||
这是在函数`myTest`内声明局部变量`loc`的例子:
|
||||
Here is a function `myTest` with a local variable called `loc`.
|
||||
|
||||
```js
|
||||
function myTest() {
|
||||
@ -22,27 +22,33 @@ myTest(); // logs "foo"
|
||||
console.log(loc); // loc is not defined
|
||||
```
|
||||
|
||||
在函数外,`loc`是未定义的。
|
||||
`loc` is not defined outside of the function.
|
||||
|
||||
# --instructions--
|
||||
|
||||
在函数`myFunction`内部声明一个局部变量`myVar`,并删除外部的 console.log。
|
||||
The editor has two `console.log`s to help you see what is happening. Check the console as you code to see how it changes. Declare a local variable `myVar` inside `myLocalScope` and run the tests.
|
||||
|
||||
**提示:**
|
||||
如果你遇到了问题,可以先尝试刷新页面。
|
||||
**Note:** The console will still have 'ReferenceError: myVar is not defined', but this will not cause the tests to fail.
|
||||
|
||||
# --hints--
|
||||
|
||||
未找到全局的`myVar`变量。
|
||||
The code should not contain a global `myVar` variable.
|
||||
|
||||
```js
|
||||
assert(typeof myVar === 'undefined');
|
||||
function declared() {
|
||||
myVar;
|
||||
}
|
||||
assert.throws(declared, ReferenceError);
|
||||
```
|
||||
|
||||
需要定义局部的`myVar`变量。
|
||||
You should add a local `myVar` variable.
|
||||
|
||||
```js
|
||||
assert(/var\s+myVar/.test(code));
|
||||
assert(
|
||||
/functionmyLocalScope\(\)\{.+(var|let|const)myVar[\s\S]*}/.test(
|
||||
__helpers.removeWhiteSpace(code)
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5690307fddb111c6084545d7
|
||||
title: if else 语句中的逻辑顺序
|
||||
title: Logical Order in If Else Statements
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cwNvMUV'
|
||||
forumTopicId: 18228
|
||||
@ -9,13 +9,13 @@ dashedName: logical-order-in-if-else-statements
|
||||
|
||||
# --description--
|
||||
|
||||
`if`、`else if`语句中代码的执行顺序是很重要的。
|
||||
Order is important in `if`, `else if` statements.
|
||||
|
||||
在条件判断语句中,代码的执行顺序是从上到下,所以你需要考虑清楚先执行哪一句,后执行哪一句。
|
||||
The function is executed from top to bottom so you will want to be careful of what statement comes first.
|
||||
|
||||
这有两个例子。
|
||||
Take these two functions as an example.
|
||||
|
||||
第一个例子:
|
||||
Here's the first:
|
||||
|
||||
```js
|
||||
function foo(x) {
|
||||
@ -29,7 +29,7 @@ function foo(x) {
|
||||
}
|
||||
```
|
||||
|
||||
第二个例子更改了代码的执行顺序:
|
||||
And the second just switches the order of the statements:
|
||||
|
||||
```js
|
||||
function bar(x) {
|
||||
@ -43,7 +43,7 @@ function bar(x) {
|
||||
}
|
||||
```
|
||||
|
||||
这两个函数看起来几乎一模一样,我们传一个值进去看看它们有什么区别。
|
||||
While these two functions look nearly identical if we pass a number to both we get different outputs.
|
||||
|
||||
```js
|
||||
foo(0) // "Less than one"
|
||||
@ -52,23 +52,23 @@ bar(0) // "Less than two"
|
||||
|
||||
# --instructions--
|
||||
|
||||
更改函数的逻辑顺序以便通过所有的测试用例。
|
||||
Change the order of logic in the function so that it will return the correct statements in all cases.
|
||||
|
||||
# --hints--
|
||||
|
||||
`orderMyLogic(4)`应该返回 "Less than 5"。
|
||||
`orderMyLogic(4)` should return "Less than 5"
|
||||
|
||||
```js
|
||||
assert(orderMyLogic(4) === 'Less than 5');
|
||||
```
|
||||
|
||||
`orderMyLogic(6)`应该返回 "Less than 10"。
|
||||
`orderMyLogic(6)` should return "Less than 10"
|
||||
|
||||
```js
|
||||
assert(orderMyLogic(6) === 'Less than 10');
|
||||
```
|
||||
|
||||
`orderMyLogic(11)`应该返回 "Greater than or equal to 10"。
|
||||
`orderMyLogic(11)` should return "Greater than or equal to 10"
|
||||
|
||||
```js
|
||||
assert(orderMyLogic(11) === 'Greater than or equal to 10');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392cc
|
||||
title: 使用 pop() 操作数组
|
||||
title: Manipulate Arrays With pop()
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRbVZAB'
|
||||
forumTopicId: 18236
|
||||
@ -9,11 +9,11 @@ dashedName: manipulate-arrays-with-pop
|
||||
|
||||
# --description--
|
||||
|
||||
改变数组中数据的另一种方法是用`.pop()`函数。
|
||||
Another way to change the data in an array is with the `.pop()` function.
|
||||
|
||||
`.pop()`函数用来“抛出”一个数组末尾的值。我们可以把这个“抛出”的值赋给一个变量存储起来。换句话说就是`.pop()`函数移除数组末尾的元素并返回这个元素。
|
||||
`.pop()` is used to "pop" a value off of the end of an array. We can store this "popped off" value by assigning it to a variable. In other words, `.pop()` removes the last element from an array and returns that element.
|
||||
|
||||
数组中任何类型的元素(数值,字符串,甚至是数组)可以被“抛出来” 。
|
||||
Any type of entry can be "popped" off of an array - numbers, strings, even nested arrays.
|
||||
|
||||
```js
|
||||
var threeArr = [1, 4, 6];
|
||||
@ -24,11 +24,11 @@ console.log(threeArr); // Returns [1, 4]
|
||||
|
||||
# --instructions--
|
||||
|
||||
使用`.pop()`函数移除`myArray`中的最后一个元素,并且把“抛出”的值赋给`removedFromMyArray`。
|
||||
Use the `.pop()` function to remove the last item from `myArray`, assigning the "popped off" value to `removedFromMyArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray`应该只包含`[["John", 23]]`。
|
||||
`myArray` should only contain `[["John", 23]]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -42,13 +42,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
对`myArray`使用`pop()`函数。
|
||||
You should use `pop()` on `myArray`.
|
||||
|
||||
```js
|
||||
assert(/removedFromMyArray\s*=\s*myArray\s*.\s*pop\s*(\s*)/.test(code));
|
||||
```
|
||||
|
||||
`removedFromMyArray`应该只包含`["cat", 2]`。
|
||||
`removedFromMyArray` should only contain `["cat", 2]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user