chore(i8n,learn): processed translations

This commit is contained in:
Crowdin Bot
2021-02-06 04:42:36 +00:00
committed by Mrugesh Mohapatra
parent 15047f2d90
commit e5c44a3ae5
3274 changed files with 172122 additions and 14164 deletions

View File

@ -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(

View File

@ -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--

View File

@ -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));

View File

@ -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));

View File

@ -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);

View File

@ -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);

View File

@ -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));

View File

@ -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));

View File

@ -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));

View File

@ -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);

View File

@ -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);

View File

@ -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));

View File

@ -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--

View File

@ -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(

View File

@ -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');

View File

@ -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
```

View File

@ -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));

View File

@ -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);

View File

@ -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);

View File

@ -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(/(?!!==)!=/));

View File

@ -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);

View File

@ -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);

View File

@ -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);

View File

@ -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);

View File

@ -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');

View File

@ -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');

View File

@ -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(

View File

@ -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(

View File

@ -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(

View File

@ -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(

View File

@ -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));

View File

@ -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--

View File

@ -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);

View File

@ -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]);

View File

@ -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&#x3C;=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(

View File

@ -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);

View File

@ -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.
`变量`非常类似于你在数学中使用的 xy 变量,都是以一个简单命名的名称来代替我们赋值给它的数据。计算机中的`变量`与数学中的变量不同的是,计算机可以在不同的时间存储不同类型的变量。
`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
```

View File

@ -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
```

View File

@ -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));

View File

@ -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--

View File

@ -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);

View File

@ -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));

View File

@ -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');

View File

@ -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--

View File

@ -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/));

View File

@ -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 = 117 是奇数)<br>48 % 2 = 048 是偶数)</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--

View File

@ -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);

View File

@ -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--

View File

@ -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(

View File

@ -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);

View File

@ -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));

View File

@ -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>&#x3C;= 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!');

View File

@ -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));

View File

@ -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
```

View File

@ -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');

View File

@ -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));

View File

@ -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]);

View File

@ -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--

View File

@ -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--

View File

@ -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]);

View File

@ -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--

View File

@ -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--

View File

@ -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');

View File

@ -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(

View File

@ -1,6 +1,6 @@
---
id: 56bbb991ad1ed5201cd392cb
title: 使用 push() 操作数组
title: Manipulate Arrays With push()
challengeType: 1
videoUrl: 'https://scrimba.com/c/cnqmVtJ'
forumTopicId: 18237
@ -9,23 +9,29 @@ dashedName: manipulate-arrays-with-push
# --description--
一个简单的方法将数据添加到一个数组的末尾是通过`push()`函数。
An easy way to append data to the end of an array is via the `push()` function.
`.push()`接受一个或多个参数,并把它“推”入到数组的末尾。
`.push()` takes one or more <dfn>parameters</dfn> and "pushes" them onto the end of the array.
Examples:
```js
var arr = [1,2,3];
arr.push(4);
// arr is now [1,2,3,4]
var arr1 = [1,2,3];
arr1.push(4);
// arr1 is now [1,2,3,4]
var arr2 = ["Stimpson", "J", "cat"];
arr2.push(["happy", "joy"]);
// arr2 now equals ["Stimpson", "J", "cat", ["happy", "joy"]]
```
# --instructions--
`["dog", 3]`“推”入到`myArray`变量的末尾。
Push `["dog", 3]` onto the end of the `myArray` variable.
# --hints--
`myArray`应该等于`[["John", 23], ["cat", 2], ["dog", 3]]`
`myArray` should now equal `[["John", 23], ["cat", 2], ["dog", 3]]`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56bbb991ad1ed5201cd392cd
title: 使用 shift() 操作数组
title: Manipulate Arrays With shift()
challengeType: 1
videoUrl: 'https://scrimba.com/c/cRbVETW'
forumTopicId: 18238
@ -9,17 +9,25 @@ dashedName: manipulate-arrays-with-shift
# --description--
`pop()`函数用来移出数组中最后一个元素。如果想要移出第一个元素要怎么办呢?
`pop()` always removes the last element of an array. What if you want to remove the first?
这就是`.shift()`的用武之地。它的工作原理就像`.pop()`,但它移除的是第一个元素,而不是最后一个。
That's where `.shift()` comes in. It works just like `.pop()`, except it removes the first element instead of the last.
Example:
```js
var ourArray = ["Stimpson", "J", ["cat"]];
var removedFromOurArray = ourArray.shift();
// removedFromOurArray now equals "Stimpson" and ourArray now equals ["J", ["cat"]].
```
# --instructions--
使用`.shift()`函数移出`myArray`中的第一项,并把“移出”的值赋给`removedFromMyArray`
Use the `.shift()` function to remove the first item from `myArray`, assigning the "shifted off" value to `removedFromMyArray`.
# --hints--
`myArray`应该等于`[["dog", 3]]`
`myArray` should now equal `[["dog", 3]]`.
```js
assert(
@ -33,7 +41,7 @@ assert(
);
```
`removedFromMyArray`应该包含`["John", 23]`
`removedFromMyArray` should contain `["John", 23]`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56bbb991ad1ed5201cd392ce
title: 使用 unshift() 操作数组
title: Manipulate Arrays With unshift()
challengeType: 1
videoUrl: 'https://scrimba.com/c/ckNDESv'
forumTopicId: 18239
@ -9,17 +9,26 @@ dashedName: manipulate-arrays-with-unshift
# --description--
你不仅可以`shift`(移出)数组中的第一个元素,你也可以`unshift`(移入)一个元素到数组的头部。
Not only can you `shift` elements off of the beginning of an array, you can also `unshift` elements to the beginning of an array i.e. add elements in front of the array.
`.unshift()`函数用起来就像`.push()`函数一样, 但不是在数组的末尾添加元素,而是在数组的头部添加元素。
`.unshift()` works exactly like `.push()`, but instead of adding the element at the end of the array, `unshift()` adds the element at the beginning of the array.
Example:
```js
var ourArray = ["Stimpson", "J", "cat"];
ourArray.shift(); // ourArray now equals ["J", "cat"]
ourArray.unshift("Happy");
// ourArray now equals ["Happy", "J", "cat"]
```
# --instructions--
使用`unshift()`函数把`["Paul",35]`加入到`myArray`的头部。
Add `["Paul",35]` to the beginning of the `myArray` variable using `unshift()`.
# --hints--
`myArray`应该包含\[["Paul", 35], ["dog", 3]]
`myArray` should now have \[["Paul", 35], ["dog", 3]].
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244cb
title: 操作复杂对象
title: Manipulating Complex Objects
challengeType: 1
videoUrl: 'https://scrimba.com/c/c9yNMfR'
forumTopicId: 18208
@ -9,9 +9,9 @@ dashedName: manipulating-complex-objects
# --description--
有时你可能希望将数据存储在灵活的<dfn>数据结构</dfn>中。JavaScript 对象是处理灵活数据的一种方法。它可以储存<dfn>字符串</dfn><dfn>数字</dfn><dfn>布尔值</dfn><dfn>函数</dfn>,和<dfn>对象</dfn>以及这些值的任意组合。
Sometimes you may want to store data in a flexible <dfn>Data Structure</dfn>. A JavaScript object is one way to handle flexible data. They allow for arbitrary combinations of <dfn>strings</dfn>, <dfn>numbers</dfn>, <dfn>booleans</dfn>, <dfn>arrays</dfn>, <dfn>functions</dfn>, and <dfn>objects</dfn>.
这是一个复杂数据结构的示例:
Here's an example of a complex data structure:
```js
var ourMusic = [
@ -29,7 +29,7 @@ var ourMusic = [
];
```
这是一个对象数组,并且对象有各种关于专辑的 <dfn>详细信息</dfn>。它也有一个嵌套的`formats`的数组。附加专辑记录可以被添加到数组的最上层。 对象将数据以一种键-值对的形式保存。在上面的示例中,`"artist": "Daft Punk"`是一个具有`"artist"`键和`"Daft Punk"`值的属性。 [JavaScript Object Notation](http://www.json.org/) 简称`JSON`是用于存储数据的相关数据交换格式。
This is an array which contains one object inside. The object has various pieces of <dfn>metadata</dfn> about an album. It also has a nested `"formats"` array. If you want to add more album records, you can do this by adding records to the top level array. Objects hold data in a property, which has a key-value format. In the example above, `"artist": "Daft Punk"` is a property that has a key of `"artist"` and a value of `"Daft Punk"`. [JavaScript Object Notation](http://www.json.org/) or `JSON` is a related data interchange format used to store data.
```json
{
@ -45,40 +45,40 @@ var ourMusic = [
}
```
**提示**
数组中有多个 JSON 对象的时候,对象与对象之间要用逗号隔开。
**Note**
You will need to place a comma after every object in the array, unless it is the last object in the array.
# --instructions--
添加一个新专辑到`myMusic`的JSON对象。添加`artist``title`字符串,`release_year`数字和`formats`字符串数组。
Add a new album to the `myMusic` array. Add `artist` and `title` strings, `release_year` number, and a `formats` array of strings.
# --hints--
`myMusic`应该是一个数组。
`myMusic` should be an array
```js
assert(Array.isArray(myMusic));
```
`myMusic`应该至少包含两个元素。
`myMusic` should have at least two elements
```js
assert(myMusic.length > 1);
```
`myMusic[1]`应该是一个对象。
`myMusic[1]` should be an object
```js
assert(typeof myMusic[1] === 'object');
```
`myMusic[1]`至少要包含四个属性。
`myMusic[1]` should have at least 4 properties
```js
assert(Object.keys(myMusic[1]).length > 3);
```
`myMusic[1]`应该包含一个类型为字符串的`artist`的属性。
`myMusic[1]` should contain an `artist` property which is a string
```js
assert(
@ -86,7 +86,7 @@ assert(
);
```
`myMusic[1]`应该包含一个类型为字符串的`title`的属性。
`myMusic[1]` should contain a `title` property which is a string
```js
assert(
@ -94,7 +94,7 @@ assert(
);
```
`myMusic[1]`应该包含一个类型为数字的`release_year` 应该包含一个类型为数字的属性。
`myMusic[1]` should contain a `release_year` property which is a number
```js
assert(
@ -103,7 +103,7 @@ assert(
);
```
`myMusic[1]`应该包含一个类型为数组的`formats`属性。
`myMusic[1]` should contain a `formats` property which is an array
```js
assert(
@ -111,7 +111,7 @@ assert(
);
```
`formats`应该是一个至少包含两个字符串元素的数组。
`formats` should be an array of strings with at least two elements
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: cf1111c1c11feddfaeb8bdef
title: 通过索引修改数组中的数据
title: Modify Array Data With Indexes
challengeType: 1
videoUrl: 'https://scrimba.com/c/czQM4A8'
forumTopicId: 18241
@ -9,25 +9,25 @@ dashedName: modify-array-data-with-indexes
# --description--
与字符串的数据不可变不同,数组的数据是可变的,并且可以自由地改变。
Unlike strings, the entries of arrays are <dfn>mutable</dfn> and can be changed freely.
**示例**
**Example**
```js
var ourArray = [50,40,30];
ourArray[0] = 15; // equals [15,40,30]
```
**提示**
数组名称和方括号之间不应有任何空格,如`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--
修改数组`myArray`中索引0上的值为`45`
Modify the data stored at index `0` of `myArray` to a value of `45`.
# --hints--
`myArray`的值应该 [45,64,99]
`myArray` should now be [45,64,99].
```js
assert(
@ -46,7 +46,7 @@ assert(
);
```
你应该使用正确的索引修改`myArray`的值。
You should be using correct index to modify the value in `myArray`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244df
title: 在 Switch 语句添加多个相同选项
title: Multiple Identical Options in Switch Statements
challengeType: 1
videoUrl: 'https://scrimba.com/c/cdBKWCV'
forumTopicId: 18242
@ -9,9 +9,10 @@ dashedName: multiple-identical-options-in-switch-statements
# --description--
如果你忘了给`switch`的每一条`case`添加`break`,那么直到遇见`break`为止,后续的`case`会一直执行。如果你想为多个不同的输入设置相同的结果,可以这样写:
If the `break` statement is omitted from a `switch` statement's `case`, the following `case` statement(s) are executed until a `break` is encountered. If you have multiple inputs with the same output, you can represent them in a `switch` statement like this:
```js
var result = "";
switch(val) {
case 1:
case 2:
@ -23,81 +24,81 @@ switch(val) {
}
```
这样1、2、3 都会有相同的结果。
Cases for 1, 2, and 3 will all produce the same result.
# --instructions--
请写一个`switch`语句,根据输入的`val`的范围得出对应的`answer`
Write a switch statement to set `answer` for the following ranges:
`1-3` - "Low"
`4-6` - "Mid"
`7-9` - "High"
**提示:**
你的`case`应基于范围中的每一个数字编写。
**Note**
You will need to have a `case` statement for each number in the range.
# --hints--
`sequentialSizes(1)`应该返回 "Low"
`sequentialSizes(1)` should return "Low"
```js
assert(sequentialSizes(1) === 'Low');
```
`sequentialSizes(2)`应该返回 "Low"
`sequentialSizes(2)` should return "Low"
```js
assert(sequentialSizes(2) === 'Low');
```
`sequentialSizes(3)`应该返回 "Low"
`sequentialSizes(3)` should return "Low"
```js
assert(sequentialSizes(3) === 'Low');
```
`sequentialSizes(4)`应该返回 "Mid"
`sequentialSizes(4)` should return "Mid"
```js
assert(sequentialSizes(4) === 'Mid');
```
`sequentialSizes(5)`应该返回 "Mid"
`sequentialSizes(5)` should return "Mid"
```js
assert(sequentialSizes(5) === 'Mid');
```
`sequentialSizes(6)`应该返回 "Mid"
`sequentialSizes(6)` should return "Mid"
```js
assert(sequentialSizes(6) === 'Mid');
```
`sequentialSizes(7)`应该返回 "High"
`sequentialSizes(7)` should return "High"
```js
assert(sequentialSizes(7) === 'High');
```
`sequentialSizes(8)`应该返回 "High"
`sequentialSizes(8)` should return "High"
```js
assert(sequentialSizes(8) === 'High');
```
`sequentialSizes(9)`应该返回 "High"
`sequentialSizes(9)` should return "High"
```js
assert(sequentialSizes(9) === 'High');
```
你不应使用`if``else`语句。
You should not use any `if` or `else` statements
```js
assert(!/else/g.test(code) || !/if/g.test(code));
```
你应该编写 9 个`case`语句。
You should have nine `case` statements
```js
assert(code.match(/case/g).length === 9);

View File

@ -1,6 +1,6 @@
---
id: bd7993c9c69feddfaeb7bdef
title: 两个小数相乘
title: Multiply Two Decimals with JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/ce2GeHq'
forumTopicId: 301173
@ -9,23 +9,23 @@ dashedName: multiply-two-decimals-with-javascript
# --description--
JavaScript 中,你也可以用小数进行计算,就像整数一样。
In JavaScript, you can also perform calculations with decimal numbers, just like whole numbers.
把两个小数相乘,并得到它们乘积。
Let's multiply two decimals together to get their product.
# --instructions--
改变`0.0`的数值让变量`product`的值等于`5.0`
Change the `0.0` so that product will equal `5.0`.
# --hints--
变量`product`应该等于`5.0`
The variable `product` should equal `5.0`.
```js
assert(product === 5.0);
```
要使用`*`运算符。
You should use the `*` operator
```js
assert(/\*/.test(code));

View File

@ -1,6 +1,6 @@
---
id: cf1231c1c11feddfaeb5bdef
title: 乘法运算
title: Multiply Two Numbers with JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/cP3y3Aq'
forumTopicId: 18243
@ -9,11 +9,11 @@ dashedName: multiply-two-numbers-with-javascript
# --description--
我们也可在 JavaScript 中使用乘法运算。
We can also multiply one number by another.
JavaScript 使用`*`符号表示两数相乘。
JavaScript uses the `*` symbol for multiplication of two numbers.
**示例**
**Example**
```js
myVar = 13 * 13; // assigned 169
@ -21,17 +21,17 @@ myVar = 13 * 13; // assigned 169
# --instructions--
改变数值`0`来让变量 product 的值等于`80`
Change the `0` so that product will equal `80`.
# --hints--
要使`product`的值等于 80
The variable `product` should be equal to 80.
```js
assert(product === 80);
```
使用`*`运算符。
You should use the `*` operator.
```js
assert(/\*/.test(code));

View File

@ -1,6 +1,6 @@
---
id: cf1111c1c11feddfaeb7bdef
title: 将一个数组嵌套在另一个数组中
title: Nest one Array within Another Array
challengeType: 1
videoUrl: 'https://scrimba.com/c/crZQZf8'
forumTopicId: 18247
@ -9,15 +9,21 @@ dashedName: nest-one-array-within-another-array
# --description--
你也可以在数组中包含其他数组,例如:`[["Bulls", 23], ["White Sox", 45]]`。这被称为一个<dfn>多维数组<dfn></dfn></dfn>
You can also nest arrays within other arrays, like below:
```js
[["Bulls", 23], ["White Sox", 45]]
```
This is also called a <dfn>multi-dimensional array<dfn>.</dfn></dfn>
# --instructions--
创建一个名为`myArray`的多维数组。
Create a nested array called `myArray`.
# --hints--
应该包含至少一个嵌入的数组。
`myArray` should have at least one array nested within another array.
```js
assert(Array.isArray(myArray) && myArray.some(Array.isArray));

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244e1
title: 循环嵌套
title: Nesting For Loops
challengeType: 1
videoUrl: 'https://scrimba.com/c/cRn6GHM'
forumTopicId: 18248
@ -9,7 +9,7 @@ dashedName: nesting-for-loops
# --description--
如果你有一个二维数组,可以使用相同的逻辑,先遍历外面的数组,再遍历里面的子数组。下面是一个例子:
If you have a multi-dimensional array, you can use the same logic as the prior waypoint to loop through both the array and any sub-arrays. Here is an example:
```js
var arr = [
@ -22,21 +22,21 @@ for (var i=0; i < arr.length; i++) {
}
```
一次输出`arr`中的每个子元素。提示,对于内部循环,我们可以通过`arr[i]``.length`来获得子数组的长度,因为`arr[i]`的本身就是一个数组。
This outputs each sub-element in `arr` one at a time. Note that for the inner loop, we are checking the `.length` of `arr[i]`, since `arr[i]` is itself an array.
# --instructions--
修改函数`multiplyAll`,获得`arr`内部数组的每个数字相乘的结果`product`
Modify function `multiplyAll` so that it returns the product of all the numbers in the sub-arrays of `arr`.
# --hints--
`multiplyAll([[1],[2],[3]])`应该返回 `6`
`multiplyAll([[1],[2],[3]])` should return `6`
```js
assert(multiplyAll([[1], [2], [3]]) === 6);
```
`multiplyAll([[1,2],[3,4],[5,6,7]])`应该返回 `5040`
`multiplyAll([[1,2],[3,4],[5,6,7]])` should return `5040`
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
`multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])`应该返回 `54`
`multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])` should return `54`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244bd
title: 将值传递给带有参数的函数
title: Passing Values to Functions with Arguments
challengeType: 1
videoUrl: 'https://scrimba.com/c/cy8rahW'
forumTopicId: 18254
@ -9,9 +9,9 @@ dashedName: passing-values-to-functions-with-arguments
# --description--
函数的参数`parameters`在函数中充当占位符(也叫形参)的作用,参数可以为一个或多个。调用一个函数时所传入的参数为实参,实参决定着形参真正的值。简单理解:形参即形式、实参即内容。
<dfn>Parameters</dfn> are variables that act as placeholders for the values that are to be input to a function when it is called. When a function is defined, it is typically defined along with one or more parameters. The actual values that are input (or <dfn>"passed"</dfn>) into a function when it is called are known as <dfn>arguments</dfn>.
这是带有两个参数的函数,`param1``param2`
Here is a function with two parameters, `param1` and `param2`:
```js
function testFun(param1, param2) {
@ -19,21 +19,21 @@ function testFun(param1, param2) {
}
```
接着我们调用`testFun` `testFun("Hello", "World");` 我们传递了两个参数,`"Hello"``"World"`。在函数内部,`param1`等于“Hello”`param2`等于“World”。请注意`testFun`函数可以多次调用,每次调用时传递的参数会决定形参的实际值。
Then we can call `testFun`: `testFun("Hello", "World");` We have passed two arguments, `"Hello"` and `"World"`. Inside the function, `param1` will equal "Hello" and `param2` will equal "World". Note that you could call `testFun` again with different arguments and the parameters would take on the value of the new arguments.
# --instructions--
<ol><li>创建一个名为<code>functionWithArgs</code>的函数,它可以接收两个参数,计算参数的和,将结果输出到控制台。</li><li>调用这个函数。</li></ol>
<ol><li>Create a function called <code>functionWithArgs</code> that accepts two arguments and outputs their sum to the dev console.</li><li>Call the function with two numbers as arguments.</li></ol>
# --hints--
`functionWithArgs`应该是一个函数。
`functionWithArgs` should be a function.
```js
assert(typeof functionWithArgs === 'function');
```
`functionWithArgs(1,2)`应该输出`3`
`functionWithArgs(1,2)` should output `3`.
```js
if (typeof functionWithArgs === 'function') {
@ -44,7 +44,7 @@ if (typeof functionWithArgs === 'function') {
assert(logOutput == 3);
```
`functionWithArgs(7,9)`应该输出`16`
`functionWithArgs(7,9)` should output `16`.
```js
if (typeof functionWithArgs === 'function') {
@ -55,10 +55,14 @@ if (typeof functionWithArgs === 'function') {
assert(logOutput == 16);
```
在你定义`functionWithArgs`之后记得调用它。
You should call `functionWithArgs` with two numbers after you define it.
```js
assert(/^\s*functionWithArgs\s*\(\s*\d+\s*,\s*\d+\s*\)\s*;?/m.test(code));
assert(
/functionWithArgs\([-+]?\d*\.?\d*,[-+]?\d*\.?\d*\)/.test(
code.replace(/\s/g, '')
)
);
```
# --seed--
@ -101,7 +105,6 @@ if (typeof functionWithArgs !== "function") {
```
## --seed-contents--
```js
```

View File

@ -1,6 +1,6 @@
---
id: 599a789b454f2bbd91a3ff4d
title: 比较不同值
title: Practice comparing different values
challengeType: 1
videoUrl: 'https://scrimba.com/c/cm8PqCa'
forumTopicId: 301174
@ -9,21 +9,19 @@ dashedName: practice-comparing-different-values
# --description--
在上两个挑战中,我们学习了相等运算符 (`==`) 和严格相等运算符 (`===`)。现在让我们快速回顾并实践一下。
In the last two challenges, we learned about the equality operator (`==`) and the strict equality operator (`===`). Let's do a quick review and practice using these operators some more.
如果要比较的值不是同一类型,相等运算符会先执行数据类型转换,然后比较值。而严格相等运算符只比较值,不会进行数据类型转换。
If the values being compared are not of the same type, the equality operator will perform a type conversion, and then evaluate the values. However, the strict equality operator will compare both the data type and value as-is, without converting one type to the other.
由此可见,相等运算符和严格相等运算符的区别是:前者会执行隐式类型转换,后者不会。
**示例**
**Examples**
```js
3 == '3' // returns true because JavaScript performs type conversion from string to number
3 === '3' // returns false because the types are different and type conversion is not performed
```
**提示**
JavaScript中,你可以使用`typeof`运算符确定变量的类型或值,如下所示:
**Note**
In JavaScript, you can determine the type of a variable or a value with the `typeof` operator, as follows:
```js
typeof 3 // returns 'number'
@ -32,23 +30,23 @@ typeof '3' // returns 'string'
# --instructions--
编辑器中的`compareEquality`函数使用相等运算符比较两个值。修改函数,使其仅在值严格相等时返回 "Equal" 。
The `compareEquality` function in the editor compares two values using the equality operator. Modify the function so that it returns "Equal" only when the values are strictly equal.
# --hints--
`compareEquality(10, "10")`应该返回 "Not Equal"
`compareEquality(10, "10")` should return "Not Equal"
```js
assert(compareEquality(10, '10') === 'Not Equal');
```
`compareEquality("20", 20)`应该返回 "Not Equal"
`compareEquality("20", 20)` should return "Not Equal"
```js
assert(compareEquality('20', 20) === 'Not Equal');
```
你应该使用`===`运算符。
You should use the `===` operator
```js
assert(code.match(/===/g));

View File

@ -1,6 +1,6 @@
---
id: 5688e62ea601b2482ff8422b
title: 资料查找
title: Profile Lookup
challengeType: 1
videoUrl: 'https://scrimba.com/c/cDqW2Cg'
forumTopicId: 18259
@ -9,27 +9,27 @@ dashedName: profile-lookup
# --description--
我们有一个对象数组,里面存储着通讯录。
We have an array of objects representing different people in our contacts lists.
函数`lookUp`有两个预定义参数:`firstName`值和`prop`属性 。
A `lookUpProfile` function that takes `name` and a property (`prop`) as arguments has been pre-written for you.
函数将会检查通讯录中是否存在一个与传入的`firstName`相同的联系人。如果存在,那么还需要检查对应的联系人中是否存在`prop`属性。
The function should check if `name` is an actual contact's `firstName` and the given property (`prop`) is a property of that contact.
如果它们都存在,函数返回`prop`属性对应的值。
If both are true, then return the "value" of that property.
如果`firstName`值不存在,返回`"No such contact"`
If `name` does not correspond to any contacts then return `"No such contact"`.
如果`prop`属性不存在,返回`"No such property"`
If `prop` does not correspond to any valid properties of a contact found to match `name` then return `"No such property"`.
# --hints--
`"Kristian", "lastName"`应该返回 `"Vos"`
`lookUpProfile("Kristian", "lastName")` should return `"Vos"`
```js
assert(lookUpProfile('Kristian', 'lastName') === 'Vos');
```
`"Sherlock", "likes"`应该返回 `["Intriguing Cases", "Violin"]`
`lookUpProfile("Sherlock", "likes")` should return `["Intriguing Cases", "Violin"]`
```js
assert.deepEqual(lookUpProfile('Sherlock', 'likes'), [
@ -38,25 +38,25 @@ assert.deepEqual(lookUpProfile('Sherlock', 'likes'), [
]);
```
`"Harry","likes"`应该返回 an array
`lookUpProfile("Harry", "likes")` should return an array
```js
assert(typeof lookUpProfile('Harry', 'likes') === 'object');
```
`"Bob", "number"`应该返回 "No such contact"
`lookUpProfile("Bob", "number")` should return "No such contact"
```js
assert(lookUpProfile('Bob', 'number') === 'No such contact');
```
`"Bob", "potato"`应该返回 "No such contact"
`lookUpProfile("Bob", "potato")` should return "No such contact"
```js
assert(lookUpProfile('Bob', 'potato') === 'No such contact');
```
`"Akira", "address"`应该返回 "No such property"
`lookUpProfile("Akira", "address")` should return "No such property"
```js
assert(lookUpProfile('Akira', 'address') === 'No such property');

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244b4
title: 用单引号引用字符串
title: Quoting Strings with Single Quotes
challengeType: 1
videoUrl: 'https://scrimba.com/c/cbQmnhM'
forumTopicId: 18260
@ -9,38 +9,39 @@ dashedName: quoting-strings-with-single-quotes
# --description--
JavaScript 中的<dfn>字符串</dfn>可以使用开始和结束都是同类型的单引号或双引号表示,与其他一些编程语言不同的是,单引号和双引号的功能在 JavaScript 中是相同的。
<dfn>String</dfn> values in JavaScript may be written with single or double quotes, as long as you start and end with the same type of quote. Unlike some other programming languages, single and double quotes work the same in JavaScript.
```js
doubleQuoteStr = "This is a string";
singleQuoteStr = 'This is also a string';
```
当你需要在一个字符串中使用多个引号的时候,你可以使用单引号包裹双引号或者相反。常见的场景比如在字符串中包含对话的句子需要用引号包裹。另外比如在一个包含有`<a>`标签的字符串中,`<a>`标签的属性值需要用引号包裹。
The reason why you might want to use one type of quote over the other is if you want to use both in a string. This might happen if you want to save a conversation in a string and have the conversation in quotes. Another use for it would be saving an `<a>` tag with various attributes in quotes, all within a string.
```js
conversation = 'Finn exclaims to Jake, "Algebraic!"';
```
但是,如果你想在字符串中使用与最外层相同的引号,会有一些问题。要知道,字符串在开头和结尾都有相同的引号,如果在中间使用了相同的引号,字符串会提前中止并抛出错误。
However, this becomes a problem if you need to use the outermost quotes within it. Remember, a string has the same kind of quote at the beginning and end. But if you have that same quote somewhere in the middle, the string will stop early and throw an error.
```js
goodStr = 'Jake asks Finn, "Hey, let\'s go on an adventure?"';
badStr = 'Finn responds, "Let's go!"'; // Throws an error
```
在上面的`goodStr`中,通过使用反斜杠`\`转义字符可以安全地使用两种引号 **提示**
不要把反斜杠`\`和斜杠`/`搞混,它们不是一回事。
In the <dfn>goodStr</dfn> above, you can use both quotes safely by using the backslash <code>\\</code> as an escape character.
**Note:** The backslash <code>\\</code> should not be confused with the forward slash `/`. They do not do the same thing.
# --instructions--
把字符串更改为开头和结尾使用单引号的字符串,并且不包含转义字符。
Change the provided string to a string with single quotes at the beginning and end and no escape characters.
这样字符串中的`<a>`标签里面任何地方都可以使用双引号。你需要将最外层引号更改为单引号,以便删除转义字符。
Right now, the `<a>` tag in the string uses double quotes everywhere. You will need to change the outer quotes to single quotes so you can remove the escape characters.
# --hints--
删除所有`反斜杠` (`\`)
You should remove all the `backslashes` (<code>\\</code>).
```js
assert(
@ -51,7 +52,7 @@ assert(
);
```
应该要有两个单引号`'`和四个双引号`"`
You should have two single quotes `'` and four double quotes `"`.
```js
assert(code.match(/"/g).length === 4 && code.match(/'/g).length === 2);

View File

@ -1,97 +1,88 @@
---
id: 56533eb9ac21ba0edf2244cf
title: 记录集合
title: Record Collection
challengeType: 1
videoUrl: 'https://scrimba.com/c/c4mpysg'
forumTopicId: 18261
dashedName: record-collection
---
# --description--
给定一个 JSON 对象,用来表示部分音乐专辑收藏。每张专辑都有几个属性和一个唯一的 id 号作为键值。并非所有专辑都有完整的信息。
You are given a JSON object representing a part of your musical album collection. Each album has a unique id number as its key and several other properties. Not all albums have complete information.
写一个函数,根据传入的`id`(如`2548`)、`prop`(属性,如`"artist"``"tracks"`)以及`value`(值,如`"Addicted to Love"`)来修改音乐专辑收藏的数据。
You start with an `updateRecords` function that takes an object like `collection`, an `id`, a `prop` (like `artist` or `tracks`), and a `value`. Complete the function using the rules below to modify the object passed to the function.
如果属性`prop`不是`"tracks"`且值`value`不为空(`""`),则更新或设置该专辑属性的值`value`
- Your function must always return the entire object.
- If `prop` isn't `tracks` and `value` isn't an empty string, update or set that album's `prop` to `value`.
- If `prop` is `tracks` but the album doesn't have a `tracks` property, create an empty array and add `value` to it.
- If `prop` is `tracks` and `value` isn't an empty string, add `value` to the end of the album's existing `tracks` array.
- If `value` is an empty string, delete the given `prop` property from the album.
你的函数必须始终返回整个音乐专辑集合对象。
处理不完整数据有几条规则:
如果属性`prop``"tracks"`,但是专辑没有`"tracks"`属性,则在添加值之前先给`"tracks"`创建一个空数组。
如果`prop``"tracks"`,并且值`value`不为空(`""` 把值`value`添加到`tracks`数组中。
如果值`value`为空(`""`),则删除专辑的这一属性`prop`
**提示:**
[通过变量访问对象的属性](javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables)时,应使用`中括号`
Push 是一个数组方法,详情请查看[Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push).
你可以参考[操作复杂对象](/javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects)这一节的内容复习相关知识。
**Note:** A copy of the `collection` object is used for the tests.
# --hints--
执行`updateRecords(5439, "artist", "ABBA")`后,`artist`属性值应该是`"ABBA"`
After `updateRecords(collection, 5439, "artist", "ABBA")`, `artist` should be `ABBA`
```js
assert(
code.match(
/var collection = {\s*2548: {\s*album: "Slippery When Wet",\s*artist: "Bon Jovi",\s*tracks: \[\s*"Let It Rock",\s*"You Give Love a Bad Name"\s*\]\s*},\s*2468: {\s*album: "1999",\s*artist: "Prince",\s*tracks: \[\s*"1999",\s*"Little Red Corvette"\s*\]\s*},\s*1245: {\s*artist: "Robert Palmer",\s*tracks: \[ \]\s*},\s*5439: {\s*album: "ABBA Gold"\s*}\s*};/g
)
updateRecords(_recordCollection, 5439, 'artist', 'ABBA')[5439]['artist'] ===
'ABBA'
);
```
执行`updateRecords(5439, "artist", "ABBA")`后,`artist` 最后的元素应该是 `"ABBA"`
```js
assert(updateRecords(5439, 'artist', 'ABBA')[5439]['artist'] === 'ABBA');
```
执行 `updateRecords(5439, "tracks", "Take a Chance on Me")` 后,`tracks` 最后的元素应该是 `"Take a Chance on Me"`
After `updateRecords(collection, 5439, "tracks", "Take a Chance on Me")`, `tracks` should have `Take a Chance on Me` as the last element.
```js
assert(
updateRecords(5439, 'tracks', 'Take a Chance on Me')[5439]['tracks'].pop() ===
'Take a Chance on Me'
updateRecords(_recordCollection, 5439, 'tracks', 'Take a Chance on Me')[5439][
'tracks'
].pop() === 'Take a Chance on Me'
);
```
执行`updateRecords(2548, "artist", "")`后,`artist`不应被创建。
After `updateRecords(collection, 2548, "artist", "")`, `artist` should not be set
```js
updateRecords(2548, 'artist', '');
assert(!collection[2548].hasOwnProperty('artist'));
updateRecords(_recordCollection, 2548, 'artist', '');
assert(!_recordCollection[2548].hasOwnProperty('artist'));
```
执行`updateRecords(1245, "tracks", "Addicted to Love")`后,`tracks`最后的元素应该是`"Addicted to Love"`
After `updateRecords(collection, 1245, "tracks", "Addicted to Love")`, `tracks` should have `Addicted to Love` as the last element.
```js
assert(
updateRecords(1245, 'tracks', 'Addicted to Love')[1245]['tracks'].pop() ===
'Addicted to Love'
updateRecords(_recordCollection, 1245, 'tracks', 'Addicted to Love')[1245][
'tracks'
].pop() === 'Addicted to Love'
);
```
执行`updateRecords(2468, "tracks", "Free")`后,`tracks`第一个元素应该是`"1999"`
After `updateRecords(collection, 2468, "tracks", "Free")`, `tracks` should have `1999` as the first element.
```js
assert(updateRecords(2468, 'tracks', 'Free')[2468]['tracks'][0] === '1999');
assert(
updateRecords(_recordCollection, 2468, 'tracks', 'Free')[2468][
'tracks'
][0] === '1999'
);
```
执行`updateRecords(2548, "tracks", "")`后,`tracks`不应被创建。
After `updateRecords(collection, 2548, "tracks", "")`, `tracks` should not be set
```js
updateRecords(2548, 'tracks', '');
assert(!collection[2548].hasOwnProperty('tracks'));
updateRecords(_recordCollection, 2548, 'tracks', '');
assert(!_recordCollection[2548].hasOwnProperty('tracks'));
```
执行`updateRecords(1245, "album", "Riptide")`后,`album`应该是`"Riptide"`
After `updateRecords(collection, 1245, "albumTitle", "Riptide")`, `albumTitle` should be `Riptide`
```js
assert(updateRecords(1245, 'album', 'Riptide')[1245]['album'] === 'Riptide');
assert(
updateRecords(_recordCollection, 1245, 'albumTitle', 'Riptide')[1245][
'albumTitle'
] === 'Riptide'
);
```
# --seed--

View File

@ -1,6 +1,6 @@
---
id: 5cfa3679138e7d9595b9d9d4
title: 使用递归代替循环
title: Replace Loops using Recursion
challengeType: 1
videoUrl: >-
https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/
@ -10,62 +10,74 @@ dashedName: replace-loops-using-recursion
# --description--
函数调用自身的编程技巧称为递归。为了便于理解,有如下任务:计算数组内元素第 `0` 到第 `n` 的元素乘积,使用 `for` 循环, 可以这样做:
Recursion is the concept that a function can be expressed in terms of itself. To help understand this, start by thinking about the following task: multiply the first `n` elements of an array to create the product of those elements. Using a `for` loop, you could do this:
```js
function multiply(arr, n) {
var product = arr[0];
for (var i = 1; i <= n; i++) {
var product = 1;
for (var i = 0; i < n; i++) {
product *= arr[i];
}
return product;
}
```
下面是递归写法,注意代码里的 `multiply(arr, n) == multiply(arr, n - 1) * arr[n]`。这意味着可以重写 `multiply` 以调用自身而无需依赖循环。
However, notice that `multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]`. That means you can rewrite `multiply` in terms of itself and never need to use a loop.
```js
function multiply(arr, n) {
if (n <= 0) {
return arr[0];
return 1;
} else {
return multiply(arr, n - 1) * arr[n];
return multiply(arr, n - 1) * arr[n - 1];
}
}
```
递归版本的 `multiply` 详述如下。在 <dfn>base case</dfn> 里,也就是 `n <= 0` 时,返回结果,也就是 `arr[0]`。在 `n` 比 0 大的情况里,函数会调用自身,参数 n 的值为 `n - 1`。函数以相同的方式持续调用 `multiply`,直到 `n = 0` 为止。所以,所有函数都可以返回,原始的 `multiply` 返回结果。
The recursive version of `multiply` breaks down like this. In the <dfn>base case</dfn>, where `n <= 0`, it returns 1. For larger values of `n`, it calls itself, but with `n - 1`. That function call is evaluated in the same way, calling `multiply` again until `n <= 0`. At this point, all the functions can return and the original `multiply` returns the answer.
**注意:** 递归函数在没有函数调用时(在这个例子是,是当 `n <= 0` 时)必需有一个跳出结构,否则永远不会执行完毕。
**Note:** Recursive functions must have a base case when they return without calling the function again (in this example, when `n <= 0`), otherwise they can never finish executing.
# --instructions--
写一个递归函数,`sum(arr, n)`,返回递归调用数组 `arr` 从第 `0` 个到第 `n` 个元素和。
Write a recursive function, `sum(arr, n)`, that returns the sum of the first `n` elements of an array `arr`.
# --hints--
`sum([1], 0)` 应该返回 1 。
`sum([1], 0)` should equal 0.
```js
assert.equal(sum([1], 0), 1);
assert.equal(sum([1], 0), 0);
```
`sum([2, 3, 4], 1)` 应该返回 5 。
`sum([2, 3, 4], 1)` should equal 2.
```js
assert.equal(sum([2, 3, 4], 1), 5);
assert.equal(sum([2, 3, 4], 1), 2);
```
代码不应该包含任何形式的循环(`for` 或者 `while` 或者高阶函数比如 `forEach``map``filter`,或者 `reduce`)。
`sum([2, 3, 4, 5], 3)` should equal 9.
```js
assert(!removeJSComments(code).match(/for|while|forEach|map|filter|reduce/g));
assert.equal(sum([2, 3, 4, 5], 3), 9);
```
应该使用递归来解决这个问题。
Your code should not rely on any kind of loops (`for` or `while` or higher order functions such as `forEach`, `map`, `filter`, or `reduce`.).
```js
assert(removeJSComments(sum.toString()).match(/sum\(.*\)/g).length > 1);
assert(
!__helpers
.removeJSComments(code)
.match(/for|while|forEach|map|filter|reduce/g)
);
```
You should use recursion to solve this problem.
```js
assert(
__helpers.removeJSComments(sum.toString()).match(/sum\(.*\)/g).length > 1
);
```
# --seed--

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244e0
title: 用一个 Switch 语句来替代多个 if else 语句
title: Replacing If Else Chains with Switch
challengeType: 1
videoUrl: 'https://scrimba.com/c/c3JE8fy'
forumTopicId: 18266
@ -9,7 +9,7 @@ dashedName: replacing-if-else-chains-with-switch
# --description--
如果你有多个选项需要选择,`switch`语句写起来会比多个串联的`if`/`if else`语句容易些,譬如:
If you have many options to choose from, a `switch` statement can be easier to write than many chained `if`/`else if` statements. The following:
```js
if (val === 1) {
@ -21,7 +21,7 @@ if (val === 1) {
}
```
可以被下面替代:
can be replaced with:
```js
switch(val) {
@ -38,65 +38,65 @@ switch(val) {
# --instructions--
把串联的`if`/`if else`语句改成`switch`语句。
Change the chained `if`/`else if` statements into a `switch` statement.
# --hints--
不要使用`else`表达式。
You should not use any `else` statements anywhere in the editor
```js
assert(!/else/g.test(code));
```
不要使用`if`表达式。
You should not use any `if` statements anywhere in the editor
```js
assert(!/if/g.test(code));
```
你应该有至少 4 个`break`表达式。
You should have at least four `break` statements
```js
assert(code.match(/break/g).length >= 4);
```
`chainToSwitch("bob")`应该为 "Marley"
`chainToSwitch("bob")` should be "Marley"
```js
assert(chainToSwitch('bob') === 'Marley');
```
`chainToSwitch(42)`应该为 "The Answer"
`chainToSwitch(42)` should be "The Answer"
```js
assert(chainToSwitch(42) === 'The Answer');
```
`chainToSwitch(1)`应该为 "There is no
`chainToSwitch(1)` should be "There is no #1"
```js
assert(chainToSwitch(1) === 'There is no #1');
```
`chainToSwitch(99)`应该为 "Missed me by this much!"
`chainToSwitch(99)` should be "Missed me by this much!"
```js
assert(chainToSwitch(99) === 'Missed me by this much!');
```
`chainToSwitch(7)`应该为 "Ate Nine"
`chainToSwitch(7)` should be "Ate Nine"
```js
assert(chainToSwitch(7) === 'Ate Nine');
```
`chainToSwitch("John")`应该为 "" (empty string)
`chainToSwitch("John")` should be "" (empty string)
```js
assert(chainToSwitch('John') === '');
```
`chainToSwitch(156)`应该为 "" (empty string)
`chainToSwitch(156)` should be "" (empty string)
```js
assert(chainToSwitch(156) === '');

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244c2
title: 函数可以返回某个值
title: Return a Value from a Function with Return
challengeType: 1
videoUrl: 'https://scrimba.com/c/cy87wue'
forumTopicId: 18271
@ -9,9 +9,9 @@ dashedName: return-a-value-from-a-function-with-return
# --description--
我们可以通过函数的<dfn>参数</dfn>把值传入函数,也可以使用`return`语句把数据从一个函数中传出来。
We can pass values into a function with <dfn>arguments</dfn>. You can use a `return` statement to send a value back out of a function.
**示例**
**Example**
```js
function plusThree(num) {
@ -20,33 +20,33 @@ function plusThree(num) {
var answer = plusThree(5); // 8
```
`plusThree`带有一个`num`<dfn>参数</dfn>并且返回returns一个等于`num + 3`的值。
`plusThree` takes an <dfn>argument</dfn> for `num` and returns a value equal to `num + 3`.
# --instructions--
创建一个函数`timesFive`接收一个参数, 把它乘以`5`之后返回关于如何测试timesFive 函数,可以参考编辑器中最后一行的示例。
Create a function `timesFive` that accepts one argument, multiplies it by `5`, and returns the new value. See the last line in the editor for an example of how you can test your `timesFive` function.
# --hints--
`timesFive`应是一个函数。
`timesFive` should be a function
```js
assert(typeof timesFive === 'function');
```
`timesFive(5)`应该返回`25`
`timesFive(5)` should return `25`
```js
assert(timesFive(5) === 25);
```
`timesFive(2)`应该返回`10`
`timesFive(2)` should return `10`
```js
assert(timesFive(2) === 10);
```
`timesFive(0)`应该返回`0`
`timesFive(0)` should return `0`
```js
assert(timesFive(0) === 0);
@ -55,7 +55,6 @@ assert(timesFive(0) === 0);
# --seed--
## --seed-contents--
```js
```

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244c4
title: 函数执行到 return 语句就结束
title: Return Early Pattern for Functions
challengeType: 1
videoUrl: 'https://scrimba.com/c/cQe39Sq'
forumTopicId: 18272
@ -9,9 +9,9 @@ dashedName: return-early-pattern-for-functions
# --description--
当代码执行到 return 语句时函数返回一个结果就结束运行了return 后面的语句不会执行。
When a `return` statement is reached, the execution of the current function stops and control returns to the calling location.
**示例**
**Example**
```js
function myFun() {
@ -22,53 +22,59 @@ function myFun() {
myFun();
```
上面的代码输出"Hello"到控制台、返回 "World",但没有输出`"byebye"`,因为函数遇到 return 语句就退出了。
The above outputs "Hello" to the console, returns "World", but `"byebye"` is never output, because the function exits at the `return` statement.
# --instructions--
修改函数`abTest``a``b`小于0时函数立即返回一个`undefined`并退出。
Modify the function `abTest` so that if `a` or `b` are less than `0` the function will immediately exit with a value of `undefined`.
**提示**
记住[`undefined` 是一个关键字](/javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables),而不是一个字符串。
**Hint**
Remember that [`undefined` is a keyword](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables), not a string.
# --hints--
`abTest(2,2)` 应该返回一个数字。
`abTest(2,2)` should return a number
```js
assert(typeof abTest(2, 2) === 'number');
```
`abTest(2,2)` 应该返回 `8`
`abTest(2,2)` should return `8`
```js
assert(abTest(2, 2) === 8);
```
`abTest(-2,2)` 应该返回 `undefined`
`abTest(-2,2)` should return `undefined`
```js
assert(abTest(-2, 2) === undefined);
```
`abTest(2,-2)` 应该返回 `undefined`
`abTest(2,-2)` should return `undefined`
```js
assert(abTest(2, -2) === undefined);
```
`abTest(2,8)` 应该返回 `18`
`abTest(2,8)` should return `18`
```js
assert(abTest(2, 8) === 18);
```
`abTest(3,3)` 应该返回 `12`
`abTest(3,3)` should return `12`
```js
assert(abTest(3, 3) === 12);
```
`abTest(0,0)` should return `0`
```js
assert(abTest(0, 0) === 0);
```
# --seed--
## --seed-contents--

View File

@ -1,6 +1,6 @@
---
id: 5679ceb97cbaa8c51670a16b
title: 从函数返回布尔值
title: Returning Boolean Values from Functions
challengeType: 1
videoUrl: 'https://scrimba.com/c/cp62qAQ'
forumTopicId: 18273
@ -9,9 +9,9 @@ dashedName: returning-boolean-values-from-functions
# --description--
你应该还记得[相等运算符](javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator)这道挑战题。在那里我们提到,所有比较操作符都会返回 boolean:要么是`true`要么是`false`
You may recall from [Comparison with the Equality Operator](/learn/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator) that all comparison operators return a boolean `true` or `false` value.
有时人们通过 if/else 语句来做比较然后返回`true``false`
Sometimes people use an if/else statement to do a comparison, like this:
```js
function isEqual(a,b) {
@ -23,7 +23,7 @@ function isEqual(a,b) {
}
```
有一个更好的方法,因为`===`总是返回`true``false`,所以我们可以直接返回比较的结果:
But there's a better way to do this. Since `===` returns `true` or `false`, we can return the result of the comparison:
```js
function isEqual(a,b) {
@ -33,23 +33,23 @@ function isEqual(a,b) {
# --instructions--
移除`isLess`函数的`if/else`语句但不影响函数的功能。
Fix the function `isLess` to remove the `if/else` statements.
# --hints--
`isLess(10,15)`应该返回 `true`
`isLess(10,15)` should return `true`
```js
assert(isLess(10, 15) === true);
```
`isLess(15,10)`应该返回 `false`
`isLess(15,10)` should return `false`
```js
assert(isLess(15, 10) === false);
```
不应该使用 `if` 或者 `else` 语句。
You should not use any `if` or `else` statements
```js
assert(!/if|else/g.test(code));

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244dd
title: 使用 Switch 语句从许多选项中进行选择
title: Selecting from Many Options with Switch Statements
challengeType: 1
videoUrl: 'https://scrimba.com/c/c4mv4fm'
forumTopicId: 18277
@ -9,9 +9,9 @@ dashedName: selecting-from-many-options-with-switch-statements
# --description--
如果你有非常多的选项需要选择,可以使用 switch 语句。根据不同的参数值会匹配上不同的 case 分支,语句会从第一个匹配的 case 分支开始执行,直到碰到 break 就结束。
If you have many options to choose from, use a <dfn>switch</dfn> statement. A `switch` statement tests a value and can have many <dfn>case</dfn> statements which define various possible values. Statements are executed from the first matched `case` value until a `break` is encountered.
这是一个伪代码案例:
Here is an example of a `switch` statement:
```js
switch(lowercaseLetter) {
@ -24,49 +24,49 @@ switch(lowercaseLetter) {
}
```
测试`case`值使用严格相等运算符进行比较break 关键字告诉 JavaScript 停止执行语句。如果没有 break 关键字,下一个语句会继续执行。
`case` values are tested with strict equality (`===`). The `break` tells JavaScript to stop executing statements. If the `break` is omitted, the next statement will be executed.
# --instructions--
写一个测试`val`的 switch 语句,并且根据下面的条件来设置不同的`answer`
`1`- "alpha"
Write a switch statement which tests `val` and sets `answer` for the following conditions:
`1` - "alpha"
`2` - "beta"
`3`- "gamma"
`3` - "gamma"
`4` - "delta"
# --hints--
`caseInSwitch(1)` 应该有一个值为 "alpha"
`caseInSwitch(1)` should have a value of "alpha"
```js
assert(caseInSwitch(1) === 'alpha');
```
`caseInSwitch(2)` 应该有一个值为 "beta"
`caseInSwitch(2)` should have a value of "beta"
```js
assert(caseInSwitch(2) === 'beta');
```
`caseInSwitch(3)` 应该有一个值为 "gamma"
`caseInSwitch(3)` should have a value of "gamma"
```js
assert(caseInSwitch(3) === 'gamma');
```
`caseInSwitch(4)` 应该有一个值为 "delta"
`caseInSwitch(4)` should have a value of "delta"
```js
assert(caseInSwitch(4) === 'delta');
```
不能使用任何`if``else`表达式。
You should not use any `if` or `else` statements
```js
assert(!/else/g.test(code) || !/if/g.test(code));
```
你应该有至少 3 `break`表达式。
You should have at least 3 `break` statements
```js
assert(code.match(/break/g).length > 2);

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244bc
title: 购物清单
title: Shopping List
challengeType: 1
videoUrl: 'https://scrimba.com/c/c9MEKHZ'
forumTopicId: 18280
@ -9,35 +9,35 @@ dashedName: shopping-list
# --description--
创建一个名叫`myList`的购物清单,清单的数据格式就是多维数组。
Create a shopping list in the variable `myList`. The list should be a multi-dimensional array containing several sub-arrays.
每个子数组中的第一个元素应该是购买的物品名称,第二个元素应该是物品的数量,类似于:
The first element in each sub-array should contain a string with the name of the item. The second element should be a number representing the quantity i.e.
`["Chocolate Bar", 15]`
任务:你的购物清单至少应该有 5 个子数组。
There should be at least 5 sub-arrays in the list.
# --hints--
`myList`应该一个数组。
`myList` should be an array.
```js
assert(isArray);
```
你的每个子数组的第一个元素的类型都应该是字符串。
The first elements in each of your sub-arrays should all be strings.
```js
assert(hasString);
```
你的每个子数组的第二个元素的类型都应该是数字。
The second elements in each of your sub-arrays should all be numbers.
```js
assert(hasNumber);
```
你的列表中至少要包含 5 个元素。
You should have at least 5 items in your list.
```js
assert(count > 4);

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244c6
title: 排队
title: Stand in Line
challengeType: 1
videoUrl: 'https://scrimba.com/c/ca8Q8tP'
forumTopicId: 18307
@ -9,41 +9,41 @@ dashedName: stand-in-line
# --description--
在计算机科学中<dfn>队列</dfn>queue是一个抽象的数据结构队列中的条目都是有秩序的。新的条目会被加到`队列`的末尾,旧的条目会从`队列`的头部被移出。
In Computer Science a <dfn>queue</dfn> is an abstract <dfn>Data Structure</dfn> where items are kept in order. New items can be added at the back of the queue and old items are taken off from the front of the queue.
写一个函数`nextInLine`,用一个数组(`arr`)和一个数字(`item`)作为参数。
Write a function `nextInLine` which takes an array (`arr`) and a number (`item`) as arguments.
把数字添加到数组的结尾,然后移出数组的第一个元素。
Add the number to the end of the array, then remove the first element of the array.
最后`nextInLine`函数应该返回被删除的元素。
The `nextInLine` function should then return the element that was removed.
# --hints--
`nextInLine([], 5)`应该返回一个数字。
`nextInLine([], 5)` should return a number.
```js
assert.isNumber(nextInLine([], 5));
```
`nextInLine([], 1)`应该返回`1`
`nextInLine([], 1)` should return `1`
```js
assert(nextInLine([], 1) === 1);
```
`nextInLine([2], 1)`应该返回`2`
`nextInLine([2], 1)` should return `2`
```js
assert(nextInLine([2], 1) === 2);
```
`nextInLine([5,6,7,8,9], 1)`应该返回`5`
`nextInLine([5,6,7,8,9], 1)` should return `5`
```js
assert(nextInLine([5, 6, 7, 8, 9], 1) === 5);
```
`nextInLine(testArr, 10)`执行后`testArr[4]`应该是`10`
After `nextInLine(testArr, 10)`, `testArr[4]` should be `10`
```js
nextInLine(testArr, 10);
@ -90,10 +90,10 @@ testArr = [1,2,3,4,5];
```js
function nextInLine(arr, item) {
// Only change code below this line
return item;
// Only change code above this line
}

View File

@ -1,6 +1,6 @@
---
id: bd7993c9c69feddfaeb8bdef
title: 使用 JavaScript 数组将多个值存储在一个变量中
title: Store Multiple Values in one Variable using JavaScript Arrays
challengeType: 1
videoUrl: 'https://scrimba.com/c/crZQWAm'
forumTopicId: 18309
@ -9,34 +9,34 @@ dashedName: store-multiple-values-in-one-variable-using-javascript-arrays
# --description--
使用`数组`,我们可以在一个地方存储多个数据。
With JavaScript `array` variables, we can store several pieces of data in one place.
以左方括号`[`开始定义一个数组,以右方括号`]`结束,里面每个元素之间用逗号隔开,例如:
You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry, like this:
`var sandwich = ["peanut butter", "jelly", "bread"]`.
# --instructions--
创建一个包含`字符串``数字`的数组`myArray`
Modify the new array `myArray` so that it contains both a `string` and a `number` (in that order).
**提示**
如果你遇到困难,请参考文本编辑器中的示例代码。
**Hint**
Refer to the example code in the text editor if you get stuck.
# --hints--
`myArray`应该是一个`数组`
`myArray` should be an `array`.
```js
assert(typeof myArray == 'object');
```
`myArray`数组的第一个元素应该是一个`字符串`
The first item in `myArray` should be a `string`.
```js
assert(typeof myArray[0] !== 'undefined' && typeof myArray[0] == 'string');
```
`myArray`数组的第二个元素应该是一个`数字`
The second item in `myArray` should be a `number`.
```js
assert(typeof myArray[1] !== 'undefined' && typeof myArray[1] == 'number');

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244a8
title: 使用赋值运算符存储值
title: Storing Values with the Assignment Operator
challengeType: 1
videoUrl: 'https://scrimba.com/c/cEanysE'
forumTopicId: 18310
@ -9,53 +9,39 @@ dashedName: storing-values-with-the-assignment-operator
# --description--
JavaScript 中,你可以使用赋值运算符将值存储在变量中。
In JavaScript, you can store a value in a variable with the <dfn>assignment</dfn> operator (`=`).
`myVariable = 5;`
这条语句把`Number`类型的值`5`赋给变量`myVariable`
This assigns the `Number` value `5` to `myVariable`.
赋值过程是从右到左进行的。在将值分配给运算符左侧的变量之前,将解析`=`运算符右侧的所有内容。
If there are any calculations to the right of the `=` operator, those are performed before the value is assigned to the variable on the left of the operator.
```js
var myVar;
myVar = 5;
myNum = myVar;
```
数值`5`被赋给变量`myVar`中,然后再次将变量`myVar`解析为`5`并将其赋给`myNum`变量。
First, this code creates a variable named `myVar`. Then, the code assigns `5` to `myVar`. Now, if `myVar` appears again in the code, the program will treat it as if it is `5`.
# --instructions--
把数值`7`赋给变量 `a`
把变量`a`中的内容赋给变量`b`
Assign the value `7` to variable `a`.
# --hints--
不要修改注释上方的代码。
You should not change code above the specified comment.
```js
assert(/var a;/.test(code) && /var b = 2;/.test(code));
assert(/var a;/.test(code));
```
`a`的值应该是 7
`a` should have a value of 7.
```js
assert(typeof a === 'number' && a === 7);
```
`b`的值应该是 7。
```js
assert(typeof b === 'number' && b === 7);
```
你需要用`=``a`的值赋给`b`
```js
assert(/b\s*=\s*a\s*;/g.test(code));
```
# --seed--
## --before-user-code--

View File

@ -1,6 +1,6 @@
---
id: cf1111c1c11feddfaeb4bdef
title: 减法运算
title: Subtract One Number from Another with JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/cP3yQtk'
forumTopicId: 18314
@ -9,11 +9,11 @@ dashedName: subtract-one-number-from-another-with-javascript
# --description--
我们也可以在 JavaScript 中进行减法运算。
We can also subtract one number from another.
JavaScript 中使用`-`来做减法运算。
JavaScript uses the `-` symbol for subtraction.
**示例**
**Example**
```js
myVar = 12 - 6; // assigned 6
@ -21,20 +21,20 @@ myVar = 12 - 6; // assigned 6
# --instructions--
改变数字`0`让变量 difference 的值为`12`
Change the `0` so the difference is `12`.
# --hints--
要使`difference`的值等于 12
The variable `difference` should be equal to 12.
```js
assert(difference === 12);
```
只用 45 减去一个数。
You should only subtract one number from 45.
```js
assert(/var\s*difference\s*=\s*45\s*-\s*[0-9]*;(?!\s*[a-zA-Z0-9]+)/.test(code));
assert(/difference=45-33;?/.test(__helpers.removeWhiteSpace(code)));
```
# --seed--

View File

@ -1,17 +1,17 @@
---
id: 567af2437cbaa8c51670a16c
title: 测试对象的属性
title: Testing Objects for Properties
challengeType: 1
videoUrl: 'https://scrimba.com/c/cm8Q7Ua'
videoUrl: 'https://scrimba.com/c/c6Wz4ySr'
forumTopicId: 18324
dashedName: testing-objects-for-properties
---
# --description--
有时检查一个对象属性是否存在是非常有用的,我们可以用`.hasOwnProperty(propname)`方法来检查对象是否有该属性。如果有返回`true`,反之返回`false`
Sometimes it is useful to check if the property of a given object exists or not. We can use the `.hasOwnProperty(propname)` method of objects to determine if that object has the given property name. `.hasOwnProperty()` returns `true` or `false` if the property is found or not.
**示例**
**Example**
```js
var myObj = {
@ -24,26 +24,51 @@ myObj.hasOwnProperty("middle"); // false
# --instructions--
修改函数`checkObj`检查`myObj`是否有`checkProp`属性,如果属性存在,返回属性对应的值,如果不存在,返回`"Not Found"`
Modify the function `checkObj` to test if an object passed to the function (`obj`) contains a specific property (`checkProp`). If the property is found, return that property's value. If not, return `"Not Found"`.
# --hints--
`checkObj("gift")`应该返回`"pony"`
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift")` should return `"pony"`.
```js
assert(checkObj('gift') === 'pony');
assert(
checkObj({ gift: 'pony', pet: 'kitten', bed: 'sleigh' }, 'gift') === 'pony'
);
```
`checkObj("pet")`应该返回`"kitten"`
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "pet")` should return `"kitten"`.
```js
assert(checkObj('pet') === 'kitten');
assert(
checkObj({ gift: 'pony', pet: 'kitten', bed: 'sleigh' }, 'pet') === 'kitten'
);
```
`checkObj("house")`应该返回`"Not Found"`
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "house")` should return `"Not Found"`.
```js
assert(checkObj('house') === 'Not Found');
assert(
checkObj({ gift: 'pony', pet: 'kitten', bed: 'sleigh' }, 'house') ===
'Not Found'
);
```
`checkObj({city: "Seattle"}, "city")` should return `"Seattle"`.
```js
assert(checkObj({ city: 'Seattle' }, 'city') === 'Seattle');
```
`checkObj({city: "Seattle"}, "district")` should return `"Not Found"`.
```js
assert(checkObj({ city: 'Seattle' }, 'district') === 'Not Found');
```
`checkObj({pet: "kitten", bed: "sleigh"}, "gift")` should return `"Not Found"`.
```js
assert(checkObj({ pet: 'kitten', bed: 'sleigh' }, 'gift') === 'Not Found');
```
# --seed--

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244ba
title: 了解字符串的不变性
title: Understand String Immutability
challengeType: 1
videoUrl: 'https://scrimba.com/c/cWPVaUR'
forumTopicId: 18331
@ -9,16 +9,16 @@ dashedName: understand-string-immutability
# --description--
JavaScript 中,`字符串`的值是 <dfn>不可变的</dfn>,这意味着一旦字符串被创建就不能被改变。
In JavaScript, `String` values are <dfn>immutable</dfn>, which means that they cannot be altered once created.
例如,下面的代码:
For example, the following code:
```js
var myStr = "Bob";
myStr[0] = "J";
```
是不会把变量`myStr`的值改变成 "Job" 的,因为变量`myStr`是不可变的。注意,这*并不*意味着`myStr`永远不能被改变,只是字符串字面量 <dfn>string literal</dfn> 的各个字符不能被改变。改变`myStr`中的唯一方法是重新给它赋一个值,例如:
cannot change the value of `myStr` to "Job", because the contents of `myStr` cannot be altered. Note that this does *not* mean that `myStr` cannot be changed, just that the individual characters of a <dfn>string literal</dfn> cannot be changed. The only way to change `myStr` would be to assign it with a new string, like this:
```js
var myStr = "Bob";
@ -27,17 +27,17 @@ myStr = "Job";
# --instructions--
`myStr`的值改为`Hello World`
Correct the assignment to `myStr` so it contains the string value of `Hello World` using the approach shown in the example above.
# --hints--
message:`myStr`的值应该是`Hello World`
`myStr` should have a value of `Hello World`.
```js
assert(myStr === 'Hello World');
```
不要修改注释上面的代码。
You should not change the code above the specified comment.
```js
assert(/myStr = "Jello World"/.test(code));

View File

@ -1,6 +1,6 @@
---
id: bd7123c9c441eddfaeb5bdef
title: 理解布尔值
title: Understanding Boolean Values
challengeType: 1
videoUrl: 'https://scrimba.com/c/c9Me8t4'
forumTopicId: 301176
@ -9,24 +9,24 @@ dashedName: understanding-boolean-values
# --description--
另一种数据类型是<dfn>布尔</dfn>Boolean)。`布尔`值要么是`true`要么是`false`。它非常像电路开关,`true`是 “开”,`false`是 “关”。这两种状态是互斥的。
Another data type is the <dfn>Boolean</dfn>. `Booleans` may only be one of two values: `true` or `false`. They are basically little on-off switches, where `true` is "on" and `false` is "off." These two states are mutually exclusive.
**注意**
`布尔值`是不带引号的,`"true"``"false"``字符串`而不是`布尔值`,在 JavaScript 中也没有特殊含义。
**Note**
`Boolean` values are never written with quotes. The `strings` `"true"` and `"false"` are not `Boolean` and have no special meaning in JavaScript.
# --instructions--
修改`welcomeToBooleans`函数,让它返回`true`而不是`false`
Modify the `welcomeToBooleans` function so that it returns `true` instead of `false` when the run button is clicked.
# --hints--
`welcomeToBooleans()`函数应该返回一个布尔值 (true/false)
The `welcomeToBooleans()` function should return a boolean (true/false) value.
```js
assert(typeof welcomeToBooleans() === 'boolean');
```
`welcomeToBooleans()`应该返回 true
`welcomeToBooleans()` should return true.
```js
assert(welcomeToBooleans() === true);

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244ab
title: 了解变量名区分大小写
title: Understanding Case Sensitivity in Variables
challengeType: 1
videoUrl: 'https://scrimba.com/c/cd6GDcD'
forumTopicId: 18334
@ -9,15 +9,15 @@ dashedName: understanding-case-sensitivity-in-variables
# --description--
JavaScript 中所有的变量和函数名都是大小写敏感的。要区别对待大写字母和小写字母。
In JavaScript all variables and function names are case sensitive. This means that capitalization matters.
`MYVAR``MyVar``myvar`是截然不同的变量。这有可能导致出现多个相似名字的的变量。所以强烈地建议你,为了保持代码清晰不要使用这一特性。
`MYVAR` is not the same as `MyVar` nor `myvar`. It is possible to have multiple distinct variables with the same name but different casing. It is strongly recommended that for the sake of clarity, you *do not* use this language feature.
<h4>最佳实践</h4>
**Best Practice**
使用<dfn>驼峰命名法</dfn>来书写一个 Javascript 变量,在<dfn>驼峰命名法</dfn>中,变量名的第一个单词的首写字母小写,后面的单词的第一个字母大写。
Write variable names in JavaScript in <dfn>camelCase</dfn>. In <dfn>camelCase</dfn>, multi-word variable names have the first word in lowercase and the first letter of each subsequent word is capitalized.
**示例:**
**Examples:**
```js
var someVariable;
@ -27,17 +27,18 @@ var thisVariableNameIsSoLong;
# --instructions--
修改已声明的变量,让它们的命名符合<dfn>驼峰命名法</dfn>的规范。
Modify the existing declarations and assignments so their names use <dfn>camelCase</dfn>.
Do not create any new variables.
# --hints--
`studlyCapVar`应该被定义并且值为`10`
`studlyCapVar` should be defined and have a value of `10`.
```js
assert(typeof studlyCapVar !== 'undefined' && studlyCapVar === 10);
```
`properCamelCase`应该被定义并且值为`"A String"`
`properCamelCase` should be defined and have a value of `"A String"`.
```js
assert(
@ -45,25 +46,25 @@ assert(
);
```
`titleCaseOver`应该被定义并且值为`9000`
`titleCaseOver` should be defined and have a value of `9000`.
```js
assert(typeof titleCaseOver !== 'undefined' && titleCaseOver === 9000);
```
`studlyCapVar`在声明和赋值时都应该使用驼峰命名法。
`studlyCapVar` should use camelCase in both declaration and assignment sections.
```js
assert(code.match(/studlyCapVar/g).length === 2);
```
`properCamelCase` 在声明和赋值时都应该使用驼峰命名法。
`properCamelCase` should use camelCase in both declaration and assignment sections.
```js
assert(code.match(/properCamelCase/g).length === 2);
```
`titleCaseOver` 在声明和赋值时都应该使用驼峰命名法。
`titleCaseOver` should use camelCase in both declaration and assignment sections.
```js
assert(code.match(/titleCaseOver/g).length === 2);

View File

@ -1,6 +1,6 @@
---
id: 598e8944f009e646fc236146
title: 函数也可以返回 undefined
title: Understanding Undefined Value returned from a Function
challengeType: 1
videoUrl: 'https://scrimba.com/c/ce2p7cL'
forumTopicId: 301177
@ -9,9 +9,9 @@ dashedName: understanding-undefined-value-returned-from-a-function
# --description--
函数一般用`return`语句来返回值,但这不是必须的。在函数没有`return`语句的情况下,当你调用它时,该函数会执行内部代码,返回的值是`undefined`
A function can include the `return` statement but it does not have to. In the case that the function doesn't have a `return` statement, when you call it, the function processes the inner code but the returned value is `undefined`.
**示例**
**Example**
```js
var sum = 0;
@ -21,40 +21,37 @@ function addSum(num) {
addSum(3); // sum will be modified but returned value is undefined
```
`addSum`是一个没有`return`语句的函数。该函数将更改全局变量`sum`,函数的返回值为`undefined`
`addSum` is a function without a `return` statement. The function will change the global `sum` variable but the returned value of the function is `undefined`.
# --instructions--
创建一个没有任何参数的函数`addFive`。此函数使`sum`变量加 5但其返回值是`undefined`
Create a function `addFive` without any arguments. This function adds 5 to the `sum` variable, but its returned value is `undefined`.
# --hints--
`addFive`应该是一个函数。
`addFive` should be a function.
```js
assert(typeof addFive === 'function');
```
`sum`应该等于 8
Once both functions have ran, the `sum` should be equal to 8.
```js
assert(sum === 8);
```
`addFive`的返回值应该是`undefined`
Returned value from `addFive` should be `undefined`.
```js
assert(addFive() === undefined);
```
函数给变量 `sum` 加 5。
Inside the `addFive` function, you should add `5` to the `sum` variable.
```js
assert(
addFive
.toString()
.replace(/\s/g, '')
.match(/sum=sum\+5|sum\+=5/)
__helpers.removeWhiteSpace(addFive.toString()).match(/sum=sum\+5|sum\+=5/)
);
```

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244aa
title: 理解未初始化的变量
title: Understanding Uninitialized Variables
challengeType: 1
videoUrl: 'https://scrimba.com/c/cBa2JAL'
forumTopicId: 18335
@ -9,33 +9,33 @@ dashedName: understanding-uninitialized-variables
# --description--
JavaScript 中的变量被声明的时候,程序内部会给它一个初始值`undefined`。当你对一个值为`undefined`的变量进行运算操作的时候,算出来的结果将会是`NaN``NaN`的意思是<dfn>"Not a Number"</dfn>。当你用一个值是`undefined`的变量来做字符串拼接操作的时候,它会输出字符串`"undefined"`
When JavaScript variables are declared, they have an initial value of `undefined`. If you do a mathematical operation on an `undefined` variable your result will be `NaN` which means <dfn>"Not a Number"</dfn>. If you concatenate a string with an `undefined` variable, you will get a literal <dfn>string</dfn> of `"undefined"`.
# --instructions--
定义 3 个变量`a``b``c`,并且分别给他们赋值:`5``10``"I am a"`,这样它们值就不会是`undefined`了。
Initialize the three variables `a`, `b`, and `c` with `5`, `10`, and `"I am a"` respectively so that they will not be `undefined`.
# --hints--
`a`应该被定义,并且值为`6`
`a` should be defined and evaluated to have the value of `6`.
```js
assert(typeof a === 'number' && a === 6);
```
`b`应该被定义,并且值为`15`
`b` should be defined and evaluated to have the value of `15`.
```js
assert(typeof b === 'number' && b === 15);
```
`c`的值不能包含`undefined`,应该为 "I am a String!"
`c` should not contain `undefined` and should have a value of "I am a String!"
```js
assert(!/undefined/.test(c) && c === 'I am a String!');
```
不要修改第二条注释下的代码。
You should not change code below the specified comment.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56bbb991ad1ed5201cd392d1
title: 更新对象属性
title: Updating Object Properties
challengeType: 1
videoUrl: 'https://scrimba.com/c/c9yEJT4'
forumTopicId: 18336
@ -9,9 +9,9 @@ dashedName: updating-object-properties
# --description--
当你创建了一个对象后,你可以用点操作符或中括号操作符来更新对象的属性。
After you've created a JavaScript object, you can update its properties at any time just like you would update any other variable. You can use either dot or bracket notation to update.
举个例子,让我们看看`ourDog`:
For example, let's look at `ourDog`:
```js
var ourDog = {
@ -22,21 +22,21 @@ var ourDog = {
};
```
让我们更改它的名称为 "Happy Camper",这有两种方式来更新对象的`name`属性: `ourDog.name = "Happy Camper";` `ourDog["name"] = "Happy Camper";` 现在,`ourDog.name`的值就不再是 "Camper",而是 "Happy Camper"
Since he's a particularly happy dog, let's change his name to "Happy Camper". Here's how we update his object's name property: `ourDog.name = "Happy Camper";` or `ourDog["name"] = "Happy Camper";` Now when we evaluate `ourDog.name`, instead of getting "Camper", we'll get his new name, "Happy Camper".
# --instructions--
更新`myDog`对象的`name`属性,让它的名字从 "Coder" 变成 "Happy Coder"
Update the `myDog` object's name property. Let's change her name from "Coder" to "Happy Coder". You can use either dot or bracket notation.
# --hints--
更新`myDog``"name"`属性, 使其等于 "Happy Coder"
You should update `myDog`'s `"name"` property to equal "Happy Coder".
```js
assert(/happy coder/gi.test(myDog.name));
```
不要修改`myDog`的定义。
You should not edit the `myDog` definition.
```js
assert(/"name": "Coder"/.test(code));

View File

@ -1,6 +1,6 @@
---
id: bd7123c9c549eddfaeb5bdef
title: 使用方括号查找字符串中的第一个字符
title: Use Bracket Notation to Find the First Character in a String
challengeType: 1
videoUrl: 'https://scrimba.com/c/ca8JwhW'
forumTopicId: 18341
@ -9,28 +9,34 @@ dashedName: use-bracket-notation-to-find-the-first-character-in-a-string
# --description--
方括号表示法是一种在字符串中的特定`index`(索引)处获取字符的方法。
<dfn>Bracket notation</dfn> is a way to get a character at a specific `index` within a string.
大多数现代编程语言如JavaScript不同于人类从 1 开始计数。它们是从 0 开始计数,这被称为 <dfn>基于零</dfn> 的索引。
Most modern programming languages, like JavaScript, don't start counting at 1 like humans do. They start at 0. This is referred to as <dfn>Zero-based</dfn> indexing.
例如, 在单词 "Charles" 中索引 0 上的字符为 "C",所以在`var firstName = "Charles"`中,你可以使用`firstName[0]`来获得第一个位置上的字符。
For example, the character at index 0 in the word "Charles" is "C". So if `var firstName = "Charles"`, you can get the value of the first letter of the string by using `firstName[0]`.
Example:
```js
var firstName = "Charles";
var firstLetter = firstName[0]; // firstLetter is "C"
```
# --instructions--
使用方括号获取变量`lastName`中的第一个字符,并赋给变量`firstLetterOfLastName`
Use bracket notation to find the first character in the `lastName` variable and assign it to `firstLetterOfLastName`.
**提示**
如果你遇到困难了,不妨看看变量`firstLetterOfFirstName`是如何赋值的。
**Hint:** Try looking at the example above if you get stuck.
# --hints--
`firstLetterOfLastName`的值应该是`L`
The `firstLetterOfLastName` variable should have the value of `L`.
```js
assert(firstLetterOfLastName === 'L');
```
你应该使用中括号。
You should use bracket notation.
```js
assert(code.match(/firstLetterOfLastName\s*?=\s*?lastName\[.*?\]/));

View File

@ -1,6 +1,6 @@
---
id: bd7123c9c451eddfaeb5bdef
title: 使用方括号查找字符串中的最后一个字符
title: Use Bracket Notation to Find the Last Character in a String
challengeType: 1
videoUrl: 'https://scrimba.com/c/cBZQGcv'
forumTopicId: 18342
@ -9,26 +9,35 @@ dashedName: use-bracket-notation-to-find-the-last-character-in-a-string
# --description--
要获取字符串的最后一个字符,可以用字符串的长度减 1 的索引值。
In order to get the last letter of a string, you can subtract one from the string's length.
例如,在`var firstName = "Charles"`中,你可以这样操作`firstName[firstName.length - 1]`来得到字符串的最后的一个字符。
For example, if `var firstName = "Charles"`, you can get the value of the last letter of the string by using `firstName[firstName.length - 1]`.
Example:
```js
var firstName = "Charles";
var lastLetter = firstName[firstName.length - 1]; // lastLetter is "s"
```
# --instructions--
使用<dfn>方括号&lt;dfn来取得<code>lastName变量中的最后一个字符。 <strong>提示</strong><br>如果你遇到困难了,不妨看看在<code>lastLetterOfFirstName</code>变量上是怎么做的。 &lt;/dfn来取得<code></code></code></dfn>
Use <dfn>bracket notation</dfn> to find the last character in the `lastName` variable.
**Hint:** Try looking at the example above if you get stuck.
# --hints--
`lastLetterOfLastName`应该是"e"
`lastLetterOfLastName` should be "e".
```js
assert(lastLetterOfLastName === 'e');
```
你需要使用`.length`获取最后一个字符。
You should use `.length` to get the last letter.
```js
assert(code.match(/\.length/g).length === 2);
assert(code.match(/\.length/g).length > 0);
```
# --seed--

View File

@ -1,6 +1,6 @@
---
id: bd7123c9c450eddfaeb5bdef
title: 使用方括号查找字符串中的第N个字符
title: Use Bracket Notation to Find the Nth Character in a String
challengeType: 1
videoUrl: 'https://scrimba.com/c/cWPVJua'
forumTopicId: 18343
@ -9,26 +9,32 @@ dashedName: use-bracket-notation-to-find-the-nth-character-in-a-string
# --description--
你也可以使用方括号来获得一个字符串中的其他位置的字符。
You can also use <dfn>bracket notation</dfn> to get the character at other positions within a string.
请记住,程序是从`0`开始计数,所以获取第一个字符实际上是\[0]。
Remember that computers start counting at `0`, so the first character is actually the zeroth character.
Example:
```js
var firstName = "Ada";
var secondLetterOfFirstName = firstName[1]; // secondLetterOfFirstName is "d"
```
# --instructions--
让我们使用方括号,把`lastName`变量的第三个字符赋值给`thirdLetterOfLastName`
Let's try to set `thirdLetterOfLastName` to equal the third letter of the `lastName` variable using bracket notation.
**提示**
如果你遇到困难了,看看`secondLetterOfFirstName`变量是如何做的。
**Hint:** Try looking at the example above if you get stuck.
# --hints--
`thirdLetterOfLastName`的值应该是`v`
The `thirdLetterOfLastName` variable should have the value of `v`.
```js
assert(thirdLetterOfLastName === 'v');
```
你应该使用方括号。
You should use bracket notation.
```js
assert(code.match(/thirdLetterOfLastName\s*?=\s*?lastName\[.*?\]/));

Some files were not shown because too many files have changed in this diff Show More