chore(i8n,curriculum): processed translations (#41490)

Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
This commit is contained in:
camperbot
2021-03-14 21:20:39 -06:00
committed by GitHub
parent 5e563329ad
commit 903a301849
262 changed files with 2871 additions and 2708 deletions

View File

@ -29,7 +29,7 @@ dashedName: nest-an-anchor-element-within-a-paragraph
`<a href="http://freecodecamp.org"> ... </a>`
`a` 元素内的内容文本 `link to freecodecamp.org` 叫作 `anchor text`(锚文本),会显示为一个可以点击的链接:
`a` 元素内的文本 `link to freecodecamp.org` 叫作<dfn>锚文本</dfn>,会显示为一个可以点击的链接:
`<a href=" ... ">link to freecodecamp.org</a>`
@ -43,15 +43,23 @@ dashedName: nest-an-anchor-element-within-a-paragraph
# --hints--
包含一个链接到 `https://freecatphotoapp.com` `a` 元素。
该只有一个 `a` 元素。
```js
assert(
$('a[href="https://freecatphotoapp.com"]').length > 0
$('a').length === 1
);
```
`a` 元素的内容文本应为 `cat photos`
`a` 元素应该链接到 “`https://freecatphotoapp.com`
```js
assert(
$('a[href="https://freecatphotoapp.com"]').length === 1
);
```
`a` 元素应该有锚文本 `cat photos`
```js
assert(
@ -61,13 +69,13 @@ assert(
);
```
应该`a` 标签的外部创建一个新的 `p` 标签。 页面中应至少包含 3 个 `p` 标签。
应该创建一个新的 `p` 元素。 HTML 代码中应该总共有至少 3 个 `p` 标签。
```js
assert($('p') && $('p').length > 2);
```
`a` 嵌套在新创建`p` 元素
`a` 元素应该被嵌套在新的 `p` 元素
```js
assert(
@ -75,7 +83,7 @@ assert(
);
```
`p` 元素应该包含文本 `View more`请注意more 之后有一个空格)。
`p` 元素应该包含文本 `View more`在它后面有一个空格)。
```js
assert(
@ -86,7 +94,7 @@ assert(
);
```
`a` 元素<em></em> 应包含文本 `View more`
`a` 元素<em></em>应该有文本 `View more`
```js
assert(
@ -96,7 +104,7 @@ assert(
);
```
确保每个 `p` 元素结束标签。
每个 `p` 元素都应该有一个结束标签。
```js
assert(
@ -106,7 +114,7 @@ assert(
);
```
确保每个 `a` 元素结束标签。
每个 `a` 元素都应该有一个结束标签。
```js
assert(

View File

@ -36,7 +36,7 @@ dashedName: build-a-personal-portfolio-webpage
**需求 11** 导航栏应始终保持在视口顶部。
你可以通过 fork [这个 CodePen 项目](https://codepen.io/freeCodeCamp/pen/MJjpwO) 来构建你的项目, 也可以使用此 CDN 链接在任何你喜欢的环境中运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`
你可以<a href='https://codepen.io/pen?template=MJjpwO' target='_blank' rel='nofollow'>使用这个 CodePen 模版</a>创建你自己的项目,点击 `Save` 即可创建你的新项目。 也可以使用此 CDN 链接在任何你喜欢的环境中运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`
完成项目并通过所有测试后,请输入你的项目在 CodePen 上的链接并提交。

View File

@ -44,7 +44,7 @@ dashedName: build-a-product-landing-page
**需求 15** 在此 app 中,应至少使用一次 CSS 的 flexbox 布局。
你可以通过 fork [这个 CodePen 项目](https://codepen.io/freeCodeCamp/pen/MJjpwO) 来构建你的项目, 也可以使用此 CDN 链接在任何你喜欢的环境中运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`
你可以<a href='https://codepen.io/pen?template=MJjpwO' target='_blank' rel='nofollow'>使用这个 CodePen 模版</a>创建你自己的项目,点击 `Save` 即可创建你的新项目。 也可以使用此 CDN 链接在任何你喜欢的环境中运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`
完成项目并通过所有测试后,请输入你的项目在 CodePen 上的链接并提交。

View File

@ -46,7 +46,7 @@ dashedName: build-a-survey-form
**需求 16** 在表单元素内,应存在一个 `id="submit"` 的按钮,以便用户提交表单。
你可以 fork [这个 CodePen 项目](https://codepen.io/freeCodeCamp/pen/MJjpwO)来创建你的项目。 也可以使用此 CDN 链接在任何你喜欢的环境中运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`
你可以<a href='https://codepen.io/pen?template=MJjpwO' target='_blank' rel='nofollow'>使用这个 CodePen 模版</a>创建你自己的项目,点击 `Save` 即可创建你的项目。 也可以使用此 CDN 链接在任何你喜欢的环境中运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`
完成项目并通过所有测试后,请输入你的项目在 CodePen 上的链接并提交。

View File

@ -44,7 +44,7 @@ dashedName: build-a-technical-documentation-page
**需求 15** 在此 app 中,应至少使用一次媒体查询。
你可以 fork [这个 CodePen 项目](https://codepen.io/freeCodeCamp/pen/MJjpwO) 来构建你的项目。 也可以使用此 CDN 链接在任何你喜欢的环境中运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`
你可以<a href='https://codepen.io/pen?template=MJjpwO' target='_blank' rel='nofollow'>使用这个 CodePen 模版</a>创建你自己的项目,点击 `Save` 即可创建你的项目。 也可以使用此 CDN 链接在任何你喜欢的环境中运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`
完成项目并通过所有测试后,请输入你的项目在 CodePen 上的链接并提交。

View File

@ -32,7 +32,7 @@ dashedName: build-a-tribute-page
**需求 9** `img` 应在其父元素内居中。
你可以 fork [这个 CodePen 项目](https://codepen.io/freeCodeCamp/pen/MJjpwO) 来构建你的项目。 也可以使用此 CDN 链接在任何你喜欢的环境中运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`
你可以<a href='https://codepen.io/pen?template=MJjpwO' target='_blank' rel='nofollow'>使用这个 CodePen 模版</a>创建你的新项目,点击 `Save` 即可创建你的新项目。 也可以使用此 CDN 链接在任何你喜欢的环境中运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`
完成项目并通过所有测试后,请输入你的项目在 CodePen 上的链接并提交。

View File

@ -1,6 +1,6 @@
---
id: 587d78b3367417b2b2512b11
title: Add Items Using splice()
title: 使用 splice() 添加元素
challengeType: 1
forumTopicId: 301152
dashedName: add-items-using-splice
@ -8,7 +8,7 @@ dashedName: add-items-using-splice
# --description--
Remember in the last challenge we mentioned that `splice()` can take up to three parameters? Well, you can use the third parameter, comprised of one or more element(s), to add to the array. This can be incredibly useful for quickly switching out an element, or a set of elements, for another.
还记得在上个挑战中我们提到 `splice()` 方法最多可以接收 3 个参数吗? 第三个参数可以是一个或多个元素,这些元素会被添加到数组中。 这样,我们能够便捷地将数组中的一个或多个连续元素换成其他的元素。
```js
const numbers = [10, 11, 12, 12, 15];
@ -16,20 +16,20 @@ const startIndex = 3;
const amountToDelete = 1;
numbers.splice(startIndex, amountToDelete, 13, 14);
// the second entry of 12 is removed, and we add 13 and 14 at the same index
console.log(numbers);
// returns [ 10, 11, 12, 13, 14, 15 ]
```
Here, we begin with an array of numbers. Then, we pass the following to `splice()`: The index at which to begin deleting elements (3), the number of elements to be deleted (1), and the remaining arguments (13, 14) will be inserted starting at that same index. Note that there can be any number of elements (separated by commas) following `amountToDelete`, each of which gets inserted.
`12` 的第二个条目已被删除,我们在同一索引处添加 `13``14``numbers` 数组现在将会是 `[ 10, 11, 12, 13, 14, 15 ]`
在上面的代码中,数组一开始包含了若干数字。 接着,我们调用 `splice()` 方法,索引为 (3) 的地方开始删除元素,删除的元素数量是 (1)。然后,(13, 14) 是在删除位置插入的元素。 可以在 `amountToDelete` 后面传入任意数量的元素(以逗号分隔),每个都会被插入到数组中。
# --instructions--
We have defined a function, `htmlColorNames`, which takes an array of HTML colors as an argument. Modify the function using `splice()` to remove the first two elements of the array and add `'DarkSalmon'` and `'BlanchedAlmond'` in their respective places.
我们已经定义了一个 `htmlColorNames` 函数,它以一个 HTML 颜色的数组作为输入参数。 请修改这个函数,使用 `splice()` 来移除数组中的前两个元素,并在对应的位置上添加 `'DarkSalmon'` `'BlanchedAlmond'`
# --hints--
`htmlColorNames` should return `["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurquoise", "FireBrick"]`
`htmlColorNames` 应返回 `["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurquoise", "FireBrick"]`
```js
assert.deepEqual(
@ -50,19 +50,19 @@ assert.deepEqual(
);
```
The `htmlColorNames` function should utilize the `splice()` method
`htmlColorNames` 函数中应调用 `splice()` 方法。
```js
assert(/.splice/.test(code));
```
You should not use `shift()` or `unshift()`.
不应使用 `shift()` `unshift()`
```js
assert(!/shift|unshift/.test(code));
```
You should not use array bracket notation.
不应使用数组的方括号表示法。
```js
assert(!/\[\d\]\s*=/.test(code));

View File

@ -1,6 +1,6 @@
---
id: 587d7b7c367417b2b2512b18
title: Add Key-Value Pairs to JavaScript Objects
title: 将键值对添加到对象中
challengeType: 1
forumTopicId: 301153
dashedName: add-key-value-pairs-to-javascript-objects
@ -8,7 +8,7 @@ dashedName: add-key-value-pairs-to-javascript-objects
# --description--
At their most basic, objects are just collections of <dfn>key-value</dfn> pairs. In other words, they are pieces of data (<dfn>values</dfn>) mapped to unique identifiers called <dfn>properties</dfn> (<dfn>keys</dfn>). Take a look at an example:
对象object本质上是键值对<dfn>key-value pair</dfn>)的集合。 或者说,一系列被映射到唯一标识符的数据就是对象;习惯上,唯一标识符叫做属性(<dfn>property</dfn>)或者键(<dfn>key</dfn>);数据叫做值(<dfn>value</dfn>)。 让我们来看一个简单的例子:
```js
const tekkenCharacter = {
@ -18,19 +18,19 @@ const tekkenCharacter = {
};
```
The above code defines a Tekken video game character object called `tekkenCharacter`. It has three properties, each of which map to a specific value. If you want to add an additional property, such as "origin", it can be done by assigning `origin` to the object:
上面的代码定义了一个叫做 `tekkenCharacter` 的“铁拳”游戏人物对象。 它有三个属性,每个属性都对应一个特定的值。 如果我们想为它再添加一个叫做 `origin` 的属性,可以这样写:
```js
tekkenCharacter.origin = 'South Korea';
```
This uses dot notation. If you were to observe the `tekkenCharacter` object, it will now include the `origin` property. Hwoarang also had distinct orange hair. You can add this property with bracket notation by doing:
上面的代码中,我们使用了点号表示法。 如果我们现在输出 `tekkenCharacter` 对象,便可以看到它具有 `origin` 属性。 接下来,因为这个人物在游戏中有着与众不同的橘色头发, 我们可以通过方括号表示法来为它添加这个属性,像这样:
```js
tekkenCharacter['hair color'] = 'dyed orange';
```
Bracket notation is required if your property has a space in it or if you want to use a variable to name the property. In the above case, the property is enclosed in quotes to denote it as a string and will be added exactly as shown. Without quotes, it will be evaluated as a variable and the name of the property will be whatever value the variable is. Here's an example with a variable:
如果要设置的属性中存在空格或者要设置的属性是一个变量那我们必须使用方括号表示法bracket notation来为对象添加属性。 在上面的代码中我们把属性hair color放到引号里以此来表示整个字符串都是需要设置的属性。 如果我们不加上引号,那么中括号里的内容会被当作一个变量来解析,这个变量对应的值就会作为要设置的属性, 请看这段代码:
```js
const eyes = 'eye color';
@ -38,7 +38,7 @@ const eyes = 'eye color';
tekkenCharacter[eyes] = 'brown';
```
After adding all the examples, the object will look like this:
执行以上所有示例代码后,对象会变成这样:
```js
{
@ -53,35 +53,35 @@ After adding all the examples, the object will look like this:
# --instructions--
A `foods` object has been created with three entries. Using the syntax of your choice, add three more entries to it: `bananas` with a value of `13`, `grapes` with a value of `35`, and `strawberries` with a value of `27`.
我们已经为你创建了包含三个项目的 `foods` 对象。 请使用上述任意语法,来为 foods 对象添加如下三个键值对:`bananas` 属性,值为 `13``grapes` 属性,值为 `35``strawberries` 属性,值为 `27`
# --hints--
`foods` should be an object.
`foods` 应为一个对象。
```js
assert(typeof foods === 'object');
```
The `foods` object should have a key `"bananas"` with a value of `13`.
`foods` 应有一个值为 `13` `bananas` 属性。
```js
assert(foods.bananas === 13);
```
The `foods` object should have a key `"grapes"` with a value of `35`.
`foods` 应有一个值为 `35` `grapes` 属性。
```js
assert(foods.grapes === 35);
```
The `foods` object should have a key `"strawberries"` with a value of `27`.
`foods` 应有一个值为 `27` `strawberries` 属性。
```js
assert(foods.strawberries === 27);
```
The key-value pairs should be set using dot or bracket notation.
应使用点号表示法或方括号表示法来设置对象的属性。
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b7b367417b2b2512b14
title: Check For The Presence of an Element With indexOf()
title: 使用 indexOf() 检查元素是否存在
challengeType: 1
forumTopicId: 301154
dashedName: check-for-the-presence-of-an-element-with-indexof
@ -8,31 +8,33 @@ dashedName: check-for-the-presence-of-an-element-with-indexof
# --description--
Since arrays can be changed, or *mutated*, at any time, there's no guarantee about where a particular piece of data will be on a given array, or if that element even still exists. Luckily, JavaScript provides us with another built-in method, `indexOf()`, that allows us to quickly and easily check for the presence of an element on an array. `indexOf()` takes an element as a parameter, and when called, it returns the position, or index, of that element, or `-1` if the element does not exist on the array.
由于数组随时都可以修改或发生 *mutated*,我们很难保证某个数据始终处于数组中的特定位置,甚至不能保证该元素是否还存在于该数组中。 好消息是JavaScript 为我们提供了内置方法 `indexOf()`。 这个方法让我们可以方便地检查某个元素是否存在于数组中。 `indexOf()` 方法接受一个元素作为输入参数,并返回该元素在数组中的位置(索引);若该元素不存在于数组中则返回 `-1`
For example:
例如:
```js
let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];
fruits.indexOf('dates'); // returns -1
fruits.indexOf('oranges'); // returns 2
fruits.indexOf('pears'); // returns 1, the first index at which the element exists
fruits.indexOf('dates');
fruits.indexOf('oranges');
fruits.indexOf('pears');
```
`indexOf('dates')` 返回 `-1``indexOf('oranges')` 返回 `2``indexOf('pears')` 返回 `1` (每个元素存在的第一个索引)。
# --instructions--
`indexOf()` can be incredibly useful for quickly checking for the presence of an element on an array. We have defined a function, `quickCheck`, that takes an array and an element as arguments. Modify the function using `indexOf()` so that it returns `true` if the passed element exists on the array, and `false` if it does not.
`indexOf()` 在快速检查一个数组中是否存在某个元素时非常有用。 我们已经定义了一个 `quickCheck` 函数,它接受一个数组和一个元素作为输入参数。 请通过 `indexOf()` 方法修改这个函数,使得当传入的参数在数组中存在时返回 `true`,否则返回 `false`
# --hints--
The `quickCheck` function should return a boolean (`true` or `false`), not a string (`"true"` or `"false"`)
`quickCheck` 函数应返回一个布尔值(`true` `false`),而不是一个字符串(`"true"` `"false"`)。
```js
assert.isBoolean(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
```
`quickCheck(["squash", "onions", "shallots"], "mushrooms")` should return `false`
`quickCheck(["squash", "onions", "shallots"], "mushrooms")` 应返回 `false`
```js
assert.strictEqual(
@ -41,7 +43,7 @@ assert.strictEqual(
);
```
`quickCheck(["onions", "squash", "shallots"], "onions")` should return `true`
`quickCheck(["onions", "squash", "shallots"], "onions")` 应返回 `true`
```js
assert.strictEqual(
@ -50,19 +52,19 @@ assert.strictEqual(
);
```
`quickCheck([3, 5, 9, 125, 45, 2], 125)` should return `true`
`quickCheck([3, 5, 9, 125, 45, 2], 125)` 应返回 `true`
```js
assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true);
```
`quickCheck([true, false, false], undefined)` should return `false`
`quickCheck([true, false, false], undefined)` 应返回 `false`
```js
assert.strictEqual(quickCheck([true, false, false], undefined), false);
```
The `quickCheck` function should utilize the `indexOf()` method
`quickCheck` 函数中应使用 `indexOf()` 方法。
```js
assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1);

View File

@ -1,6 +1,6 @@
---
id: 587d7b7d367417b2b2512b1c
title: Check if an Object has a Property
title: 检查对象是否具有某个属性
challengeType: 1
forumTopicId: 301155
dashedName: check-if-an-object-has-a-property
@ -8,21 +8,22 @@ dashedName: check-if-an-object-has-a-property
# --description--
Now we can add, modify, and remove keys from objects. But what if we just wanted to know if an object has a specific property? JavaScript provides us with two different ways to do this. One uses the `hasOwnProperty()` method and the other uses the `in` keyword. If we have an object `users` with a property of `Alan`, we could check for its presence in either of the following ways:
我们已经学习了如何添加、修改和移除对象中的属性。 但如果我们想知道一个对象中是否包含某个属性呢? JavaScript 为我们提供了两种不同的方式来实现这个功能: 一个是通过 `hasOwnProperty()` 方法,另一个是使用 `in` 关键字。 假如我们有一个 `users` 对象,为检查它是否含有 `Alan` 属性,可以这样写:
```js
users.hasOwnProperty('Alan');
'Alan' in users;
// both return true
```
这两者结果都应该为 `true`
# --instructions--
We've created an object, `users`, with some users in it and a function `isEveryoneHere`, which we pass the `users` object to as an argument. Finish writing this function so that it returns `true` only if the `users` object contains all four names, `Alan`, `Jeff`, `Sarah`, and `Ryan`, as keys, and `false` otherwise.
我们已经定义了一个包含若干用户信息的 `users` 对象和一个 `isEveryoneHere` 函数,该函数接收 `users` 对象作为参数。 请完成该函数使其在 `users` 对象中同时包含 `Alan``Jeff``Sarah``Ryan` 四个属性时才返回 `true`,否则返回 `false`
# --hints--
The `users` object should only contain the keys `Alan`, `Jeff`, `Sarah`, and `Ryan`
`users` 对象应该只包含 `Alan``Jeff``Sarah``Ryan` 4 个属性。
```js
assert(
@ -34,13 +35,13 @@ assert(
);
```
The function `isEveryoneHere` should return `true` if `Alan`, `Jeff`, `Sarah`, and `Ryan` are properties on the `users` object
`isEveryoneHere` 函数在 `users` 对象包含 `Alan``Jeff``Sarah``Ryan` 4 个属性时应返回 `true`
```js
assert(isEveryoneHere(users) === true);
```
The function `isEveryoneHere` should return `false` if `Alan` is not a property on the `users` object
`isEveryoneHere` 函数在 `users` 对象不包含 `Alan` 时应返回 `false`
```js
assert(
@ -51,7 +52,7 @@ assert(
);
```
The function `isEveryoneHere` should return `false` if `Jeff` is not a property on the `users` object
`isEveryoneHere` 函数在 `users` 对象不包含 `Jeff` 时应返回 `false`
```js
assert(
@ -62,7 +63,7 @@ assert(
);
```
The function `isEveryoneHere` should return `false` if `Sarah` is not a property on the `users` object
`isEveryoneHere` 函数在 `users` 对象不包含 `Sarah` 时应返回 `false`
```js
assert(
@ -73,7 +74,7 @@ assert(
);
```
The function `isEveryoneHere` should return `false` if `Ryan` is not a property on the `users` object
`isEveryoneHere` 函数在 `users` 对象不包含 `Ryan` 时应返回 `false`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b7b367417b2b2512b17
title: Combine Arrays with the Spread Operator
title: 使用展开运算符合并数组
challengeType: 1
forumTopicId: 301156
dashedName: combine-arrays-with-the-spread-operator
@ -8,30 +8,31 @@ dashedName: combine-arrays-with-the-spread-operator
# --description--
Another huge advantage of the <dfn>spread</dfn> operator, is the ability to combine arrays, or to insert all the elements of one array into another, at any index. With more traditional syntaxes, we can concatenate arrays, but this only allows us to combine arrays at the end of one, and at the start of another. Spread syntax makes the following operation extremely simple:
展开语法(<dfn>spread</dfn>)的另一个重要用途是合并数组,或者将某个数组的所有元素插入到另一个数组的任意位置。 我们也可以使用 ES5 的语法连接两个数组,但只能让它们首尾相接。 而展开语法可以让这样的操作变得极其简单:
```js
let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];
let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander'];
// thatArray now equals ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']
```
Using spread syntax, we have just achieved an operation that would have been more complex and more verbose had we used traditional methods.
`thatArray` 会有值 `['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']`
使用展开语法,我们就可以很方便的实现一个用传统方法会写得很复杂且冗长的操作。
# --instructions--
We have defined a function `spreadOut` that returns the variable `sentence`. Modify the function using the <dfn>spread</dfn> operator so that it returns the array `['learning', 'to', 'code', 'is', 'fun']`.
我们已经定义了一个返回 `sentence` 变量的 `spreadOut` 函数。 请修改这个函数,利用 <dfn>spread</dfn> 使该函数返回数组 `['learning', 'to', 'code', 'is', 'fun']`
# --hints--
`spreadOut` should return `["learning", "to", "code", "is", "fun"]`
`spreadOut` 应返回 `["learning", "to", "code", "is", "fun"]`
```js
assert.deepEqual(spreadOut(), ['learning', 'to', 'code', 'is', 'fun']);
```
The `spreadOut` function should utilize spread syntax
`spreadOut` 函数里应用到展开语法。
```js
assert.notStrictEqual(spreadOut.toString().search(/[...]/), -1);

View File

@ -1,6 +1,6 @@
---
id: 587d7b7b367417b2b2512b13
title: Copy an Array with the Spread Operator
title: 使用展开运算符复制数组
challengeType: 1
forumTopicId: 301157
dashedName: copy-an-array-with-the-spread-operator
@ -8,24 +8,24 @@ dashedName: copy-an-array-with-the-spread-operator
# --description--
While `slice()` allows us to be selective about what elements of an array to copy, among several other useful tasks, ES6's new <dfn>spread operator</dfn> allows us to easily copy *all* of an array's elements, in order, with a simple and highly readable syntax. The spread syntax simply looks like this: `...`
`slice()` 可以让我们从一个数组中选择一些元素来复制到新数组中,而 ES6 中又引入了一个简洁且可读性强的语法:展开运算符(<dfn>spread operator</dfn>),它能让我们方便地复制数组中的*所有*元素。 展开语法写出来是这样:`...`
In practice, we can use the spread operator to copy an array like so:
我们可以用展开运算符来复制数组:
```js
let thisArray = [true, true, undefined, false, null];
let thatArray = [...thisArray];
// thatArray equals [true, true, undefined, false, null]
// thisArray remains unchanged and thatArray contains the same elements as thisArray
```
`thatArray` 等于 `[true, true, undefined, false, null]``thisArray` 保持不变, `thatArray` 包含与 `thisArray` 相同的元素。
# --instructions--
We have defined a function, `copyMachine` which takes `arr` (an array) and `num` (a number) as arguments. The function is supposed to return a new array made up of `num` copies of `arr`. We have done most of the work for you, but it doesn't work quite right yet. Modify the function using spread syntax so that it works correctly (hint: another method we have already covered might come in handy here!).
我们已经定义了一个 `copyMachine` 函数,它接受 `arr`(一个数组)和 `num`(一个数字)作为输入参数。 该函数需要返回一个由 `num``arr` 组成的新的二维数组。 同时,我们写好了大致的流程,只是细节实现还没有写完。 请修改这个函数,使用展开语法,使该函数能正常工作(提示:我们已经学到过的一个方法很适合用在这里)!
# --hints--
`copyMachine([true, false, true], 2)` should return `[[true, false, true], [true, false, true]]`
`copyMachine([true, false, true], 2)` 应返回 `[[true, false, true], [true, false, true]]`
```js
assert.deepEqual(copyMachine([true, false, true], 2), [
@ -34,7 +34,7 @@ assert.deepEqual(copyMachine([true, false, true], 2), [
]);
```
`copyMachine([1, 2, 3], 5)` should return `[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]`
`copyMachine([1, 2, 3], 5)` 应返回 `[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]`
```js
assert.deepEqual(copyMachine([1, 2, 3], 5), [
@ -46,13 +46,13 @@ assert.deepEqual(copyMachine([1, 2, 3], 5), [
]);
```
`copyMachine([true, true, null], 1)` should return `[[true, true, null]]`
`copyMachine([true, true, null], 1)` 应返回 `[[true, true, null]]`
```js
assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]]);
```
`copyMachine(["it works"], 3)` should return `[["it works"], ["it works"], ["it works"]]`
`copyMachine(["it works"], 3)` 应返回 `[["it works"], ["it works"], ["it works"]]`
```js
assert.deepEqual(copyMachine(['it works'], 3), [
@ -62,7 +62,7 @@ assert.deepEqual(copyMachine(['it works'], 3), [
]);
```
The `copyMachine` function should utilize the `spread operator` with array `arr`
`copyMachine` 函数中应对 `arr` 使用展开运算符(`spread operator`)。
```js
assert(__helpers.removeJSComments(code).match(/\.\.\.arr/));

View File

@ -1,6 +1,6 @@
---
id: 587d7b7a367417b2b2512b12
title: Copy Array Items Using slice()
title: 使用 slice() 复制数组元素
challengeType: 1
forumTopicId: 301158
dashedName: copy-array-items-using-slice
@ -8,25 +8,25 @@ dashedName: copy-array-items-using-slice
# --description--
The next method we will cover is `slice()`. Rather than modifying an array, `slice()` copies or *extracts* a given number of elements to a new array, leaving the array it is called upon untouched. `slice()` takes only 2 parameters — the first is the index at which to begin extraction, and the second is the index at which to stop extraction (extraction will occur up to, but not including the element at this index). Consider this:
接下来我们要介绍 `slice()` 方法。 `slice()` 不会修改数组,而是会复制,或者说*提取extract*给定数量的元素到一个新数组。 `slice()` 只接收 2 个输入参数:第一个是开始提取元素的位置(索引),第二个是提取元素的结束位置(索引)。 提取的元素中不包括第二个参数所对应的元素。 如下示例:
```js
let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
let todaysWeather = weatherConditions.slice(1, 3);
// todaysWeather equals ['snow', 'sleet'];
// weatherConditions still equals ['rain', 'snow', 'sleet', 'hail', 'clear']
```
In effect, we have created a new array by extracting elements from an existing array.
`todaysWeather` 值为 `['snow', 'sleet']``weatherConditions` 值仍然为 `['rain', 'snow', 'sleet', 'hail', 'clear']`
在上面的代码中,我们从一个数组中提取了一些元素,并用这些元素创建了一个新数组。
# --instructions--
We have defined a function, `forecast`, that takes an array as an argument. Modify the function using `slice()` to extract information from the argument array and return a new array that contains the elements `'warm'` and `'sunny'`.
我们已经定义了一个 `forecast` 函数,它接受一个数组作为参数。 请修改这个函数,利用 `slice()` 从输入的数组中提取信息,最终返回一个包含元素 `warm` `sunny` 的新数组。
# --hints--
`forecast` should return `["warm", "sunny"]`
`forecast` 应返回 `["warm", "sunny"]`
```js
assert.deepEqual(
@ -35,7 +35,7 @@ assert.deepEqual(
);
```
The `forecast` function should utilize the `slice()` method
`forecast` 函数中应使用 `slice()` 方法。
```js
assert(/\.slice\(/.test(code));

View File

@ -1,6 +1,6 @@
---
id: 587d7b7b367417b2b2512b16
title: Create complex multi-dimensional arrays
title: 创建复杂的多维数组
challengeType: 1
forumTopicId: 301159
dashedName: create-complex-multi-dimensional-arrays
@ -8,52 +8,54 @@ dashedName: create-complex-multi-dimensional-arrays
# --description--
Awesome! You have just learned a ton about arrays! This has been a fairly high level overview, and there is plenty more to learn about working with arrays, much of which you will see in later sections. But before moving on to looking at <dfn>Objects</dfn>, lets take one more look, and see how arrays can become a bit more complex than what we have seen in previous challenges.
很好! 你现在已经学到很多关于数组的知识了, 但这些只是个开始。我们将在接下来的中挑战中学到更多与数组相关的知识。 在继续学习对象(<dfn>Objects</dfn>)之前,让我们再花一点时间了解下更复杂的数组嵌套。
One of the most powerful features when thinking of arrays as data structures, is that arrays can contain, or even be completely made up of other arrays. We have seen arrays that contain arrays in previous challenges, but fairly simple ones. However, arrays can contain an infinite depth of arrays that can contain other arrays, each with their own arbitrary levels of depth, and so on. In this way, an array can very quickly become very complex data structure, known as a <dfn>multi-dimensional</dfn>, or nested array. Consider the following example:
数组的一个强大的特性是,它可以包含其他数组,甚至完全由其他数组组成。 在上一个挑战中,我们已经接触到了包含数组的数组,但它还算是比较简单的。 数组中的数组还可以再包含其他数组,即可以嵌套任意多层数组。 习惯上,我们称这种数据结构为<dfn>多维(multi-dimensional)数组</dfn>或嵌套(nested)数组。 请看如下的示例:
```js
let nestedArray = [ // top, or first level - the outer most array
['deep'], // an array within an array, 2 levels of depth
let nestedArray = [
['deep'],
[
['deeper'], ['deeper'] // 2 arrays nested 3 levels deep
['deeper'], ['deeper']
],
[
[
['deepest'], ['deepest'] // 2 arrays nested 4 levels deep
['deepest'], ['deepest']
],
[
[
['deepest-est?'] // an array nested 5 levels deep
['deepest-est?']
]
]
]
];
```
While this example may seem convoluted, this level of complexity is not unheard of, or even unusual, when dealing with large amounts of data. However, we can still very easily access the deepest levels of an array this complex with bracket notation:
`deep` 数组已嵌套 2 层。 `deeper` 数组嵌套了 3 层。 `deepest` 数组嵌套了 3 层, `deepest-est?` 嵌套了 5 层。
虽然这个例子看起来错综复杂,不过,尤其是在处理大量数据的时候,这种数据结构还是会用到的。 尽管结构复杂,不过我们仍可以通过方括号表示法来访问嵌套得最深的数组:
```js
console.log(nestedArray[2][1][0][0][0]);
// logs: deepest-est?
```
And now that we know where that piece of data is, we can reset it if we need to:
控制台打印的是字符串 `deepest-est?`。 既然我们知道数据的位置,当然,我们也可以修改它:
```js
nestedArray[2][1][0][0][0] = 'deeper still';
console.log(nestedArray[2][1][0][0][0]);
// now logs: deeper still
```
现在控制台打印的是 `deeper still`
# --instructions--
We have defined a variable, `myNestedArray`, set equal to an array. Modify `myNestedArray`, using any combination of <dfn>strings</dfn>, <dfn>numbers</dfn>, and <dfn>booleans</dfn> for data elements, so that it has exactly five levels of depth (remember, the outer-most array is level 1). Somewhere on the third level, include the string `'deep'`, on the fourth level, include the string `'deeper'`, and on the fifth level, include the string `'deepest'`.
我们已经定义了一个叫做 `myNestedArray` 的数组变量。 请修改 `myNestedArray`,使用字符串(<dfn>string</dfn>)、数字(<dfn>number</dfn>)或布尔值(<dfn>boolean</dfn>)的任意组合作为数组的元素,并让 myNestedArray 刚好有 5 层(注意,最外层的数组是第 1 层)。 同时,请在第 3 层的数组中包含字符串 `deep`;在第 4 层的数组中包含字符串 `deeper`,在第 5 层的数组中包含字符串 `deepest`
# --hints--
`myNestedArray` should contain only numbers, booleans, and strings as data elements
`myNestedArray` 中的数据元素应只包含字符串、数字或者布尔值。
```js
assert.strictEqual(
@ -77,7 +79,7 @@ assert.strictEqual(
);
```
`myNestedArray` should have exactly 5 levels of depth
`myNestedArray` 应刚好包含 5 层嵌套数组。
```js
assert.strictEqual(
@ -100,7 +102,7 @@ assert.strictEqual(
);
```
`myNestedArray` should contain exactly one occurrence of the string `"deep"` on an array nested 3 levels deep
`myNestedArray` 中应只有一个字符串 `deep`,并且应出现在第 3 层数组中。
```js
assert(
@ -129,7 +131,7 @@ assert(
);
```
`myNestedArray` should contain exactly one occurrence of the string `"deeper"` on an array nested 4 levels deep
`myNestedArray` 中应只有一个字符串 `deeper`,并且应出现在第 4 层数组中。
```js
assert(
@ -158,7 +160,7 @@ assert(
);
```
`myNestedArray` should contain exactly one occurrence of the string `"deepest"` on an array nested 5 levels deep
`myNestedArray` 中应只有一个字符串 `deepest`,并且应出现在第 5 层数组中。
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b7b367417b2b2512b15
title: Iterate Through All an Array's Items Using For Loops
title: 使用 for 循环遍历数组中的全部元素
challengeType: 1
forumTopicId: 301161
dashedName: iterate-through-all-an-arrays-items-using-for-loops
@ -8,9 +8,9 @@ dashedName: iterate-through-all-an-arrays-items-using-for-loops
# --description--
Sometimes when working with arrays, it is very handy to be able to iterate through each item to find one or more elements that we might need, or to manipulate an array based on which data items meet a certain set of criteria. JavaScript offers several built in methods that each iterate over arrays in slightly different ways to achieve different results (such as `every()`, `forEach()`, `map()`, etc.), however the technique which is most flexible and offers us the greatest amount of control is a simple `for` loop.
使用数组时,我们经常需要遍历数组的所有元素来找出我们需要的一个或多个元素,抑或是对数组执行一些特定的操作。 JavaScript 为我们提供了几个内置的方法,它们以不同的方式遍历数组,以便我们可以用于不同的场景(如 `every()``forEach()``map()` 等等)。 然而,最简单的 `for` 循环不仅能实现上述这些方法的功能,而且相比之下也会更加灵活。
Consider the following:
请看以下的例子:
```js
function greaterThanTen(arr) {
@ -24,18 +24,17 @@ function greaterThanTen(arr) {
}
greaterThanTen([2, 12, 8, 14, 80, 0, 1]);
// returns [12, 14, 80]
```
Using a `for` loop, this function iterates through and accesses each element of the array, and subjects it to a simple test that we have created. In this way, we have easily and programmatically determined which data items are greater than `10`, and returned a new array containing those items.
在这个函数中,我们用一个 `for` 循环来遍历数组,逐一对其中的元素进行判断。 通过上面的代码,我们可以找出数组中大于 `10` 的所有元素,并返回一个包含这些元素的新数组 `[12, 14, 80]`
# --instructions--
We have defined a function, `filteredArray`, which takes `arr`, a nested array, and `elem` as arguments, and returns a new array. `elem` represents an element that may or may not be present on one or more of the arrays nested within `arr`. Modify the function, using a `for` loop, to return a filtered version of the passed array such that any array nested within `arr` containing `elem` has been removed.
我们已经定义了 `filteredArray` 函数,它接受一个嵌套的数组 `arr` 和一个 `elem` 作为参数,并要返回一个新数组。 `arr` 数组中嵌套的数组里可能包含 `elem` 元素,也可能不包含。 请修改该函数,用一个 `for` 循环来做筛选,使函数返回一个由 `arr` 中不包含 `elem` 的数组所组成的新数组。
# --hints--
`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` should return `[ [10, 8, 3], [14, 6, 23] ]`
`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` 应返回 `[[10, 8, 3], [14, 6, 23]]`
```js
assert.deepEqual(
@ -54,7 +53,7 @@ assert.deepEqual(
);
```
`filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2)` should return `[ ["flutes", 4] ]`
`filteredArray([["trumpets", 2], ["flutes", 4], ["saxophones", 2]], 2)` 应返回 `[["flutes", 4]]`
```js
assert.deepEqual(
@ -70,7 +69,7 @@ assert.deepEqual(
);
```
`filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")` should return `[ ["amy", "beth", "sam"] ]`
`filteredArray([["amy", "beth", "sam"], ["dave", "sean", "peter"]], "peter")` 应返回 `[["amy", "beth", "sam"]]`
```js
assert.deepEqual(
@ -85,7 +84,7 @@ assert.deepEqual(
);
```
`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` should return `[ ]`
`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` 应返回 `[]`
```js
assert.deepEqual(
@ -102,7 +101,7 @@ assert.deepEqual(
);
```
The `filteredArray` function should utilize a `for` loop
`filteredArray` 函数中应使用 `for` 循环。
```js
assert.notStrictEqual(filteredArray.toString().search(/for/), -1);

View File

@ -1,6 +1,6 @@
---
id: 587d7b7d367417b2b2512b1d
title: Iterate Through the Keys of an Object with a for...in Statement
title: 使用 for...in 语句遍历对象
challengeType: 1
forumTopicId: 301162
dashedName: iterate-through-the-keys-of-an-object-with-a-for---in-statement
@ -8,25 +8,23 @@ dashedName: iterate-through-the-keys-of-an-object-with-a-for---in-statement
# --description--
Sometimes you may need to iterate through all the keys within an object. This requires a specific syntax in JavaScript called a <dfn>for...in</dfn> statement. For our `users` object, this could look like:
如果我们想要遍历对象中的所有属性, 只需要使用 JavaScript 中的 <dfn>for...in</dfn> 语句即可。 以遍历 `users` 对象的属性为例:
```js
for (let user in users) {
console.log(user);
}
// logs:
Alan
Jeff
Sarah
Ryan
```
In this statement, we defined a variable `user`, and as you can see, this variable was reset during each iteration to each of the object's keys as the statement looped through the object, resulting in each user's name being printed to the console. **NOTE:** Objects do not maintain an ordering to stored keys like arrays do; thus a key's position on an object, or the relative order in which it appears, is irrelevant when referencing or accessing that key.
这将在控制台打印 `Alan``Jeff``Sarah``Ryan` - 每个值占一行。
在上面的代码中,我们定义了一个 `user` 变量。 可以观察到,这个变量在遍历对象的语句执行过程中会一直被重置并赋予新值,结果就是不同的用户名打印到了 console 中。
**注意:**对象中的键是无序的,这与数组不同。 因此,一个对象中某个属性的位置,或者说它出现的相对顺序,在引用或访问该属性时是不确定的。
# --instructions--
We've defined a function `countOnline` which accepts one argument (a users object). Use a <dfn>for...in</dfn> statement within this function to loop through the users object passed into the function and return the number of users whose `online` property is set to `true`. An example of a users object which could be passed to `countOnline` is shown below. Each user will have an `online` property with either a `true` or `false` value.
我们已经定义了一个 `countOnline` 函数,它接收一个 users 对象参数。 请在其中使用 <dfn>for...in</dfn> 语句来遍历传入函数的 users 对象中的用户,并返回 `online` 属性为 `true` 的用户数量。 以下是一个传入 `countOnline` 函数的对象示例, 注意每个用户都有 `online` 属性,其属性值为 `true` `false`
```js
{
@ -44,7 +42,7 @@ We've defined a function `countOnline` which accepts one argument (a users objec
# --hints--
The function `countOnline` should use a `for in` statement to iterate through the object keys of the object passed to it.
函数 `countOnline` 中应使用 `for in` 语句遍历传入的对象的对象键。
```js
assert(
@ -54,19 +52,19 @@ assert(
);
```
The function `countOnline` should return `1` when the object `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }` is passed to it
当传入 `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }` 时,函数 `countOnline` 应该返回 `1`
```js
assert(countOnline(usersObj1) === 1);
```
The function `countOnline` should return `2` when the object `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }` is passed to it
当传入 `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }` 时,函数 `countOnline` 应该返回 `2`
```js
assert(countOnline(usersObj2) === 2);
```
The function `countOnline` should return `0` when the object `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }` is passed to it
当传入 `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }` 时,函数 `countOnline` 应该返回 `0`
```js
assert(countOnline(usersObj3) === 0);

View File

@ -1,6 +1,6 @@
---
id: 587d78b2367417b2b2512b0f
title: Remove Items from an Array with pop() and shift()
title: 使用 pop() shift() 从数组中删除元素
challengeType: 1
forumTopicId: 301165
dashedName: remove-items-from-an-array-with-pop-and-shift
@ -8,35 +8,39 @@ dashedName: remove-items-from-an-array-with-pop-and-shift
# --description--
Both `push()` and `unshift()` have corresponding methods that are nearly functional opposites: `pop()` and `shift()`. As you may have guessed by now, instead of adding, `pop()` *removes* an element from the end of an array, while `shift()` removes an element from the beginning. The key difference between `pop()` and `shift()` and their cousins `push()` and `unshift()`, is that neither method takes parameters, and each only allows an array to be modified by a single element at a time.
`push()` `unshift()` 都有一个与它们作用相反的函数:`pop()` `shift()`。 与插入元素相反,`pop()` 会从数组的末尾*移除*一个元素,而 `shift()` 会从数组的开头移除一个元素。 `pop()` `shift()` `push()` `unshift()` 的关键区别在于,用于删除元素的方法不接收参数,而且每次只能删除数组中的一个元素。
Let's take a look:
让我们来看以下的例子:
```js
let greetings = ['whats up?', 'hello', 'see ya!'];
greetings.pop();
// now equals ['whats up?', 'hello']
greetings.shift();
// now equals ['hello']
```
We can also return the value of the removed element with either method like this:
`greetings` 值为 `['whats up?', 'hello']`
```js
greetings.shift();
```
`greetings` 值为 `['hello']`
这些用于删除数组元素的方法会返回被删除的元素:
```js
let popped = greetings.pop();
// returns 'hello'
// greetings now equals []
```
`greetings` 值为 `[]``popped` 值为 `hello`
# --instructions--
We have defined a function, `popShift`, which takes an array as an argument and returns a new array. Modify the function, using `pop()` and `shift()`, to remove the first and last elements of the argument array, and assign the removed elements to their corresponding variables, so that the returned array contains their values.
我们已经定义了一个 `popShift` 函数,它接收一个数组作为输入参数并返回一个新的数组。 请修改这个函数,使用 `pop()` `shift()` 来移除输入的数组中的第一个元素和最后一个元素,并将这两个被移除的元素分别赋值给对应的变量,使得最终返回的数组里包含这两个值。
# --hints--
`popShift(["challenge", "is", "not", "complete"])` should return `["challenge", "complete"]`
`popShift(["challenge", "is", "not", "complete"])` 应返回 `["challenge", "complete"]`
```js
assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [
@ -45,13 +49,13 @@ assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [
]);
```
The `popShift` function should utilize the `pop()` method
`popShift` 函数中应使用 `pop()` 方法。
```js
assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1);
```
The `popShift` function should utilize the `shift()` method
`popShift` 函数中应使用 `shift()` 方法。
```js
assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1);

View File

@ -1,6 +1,6 @@
---
id: 587d78b2367417b2b2512b10
title: Remove Items Using splice()
title: 使用 splice() 删除元素
challengeType: 1
forumTopicId: 301166
dashedName: remove-items-using-splice
@ -8,34 +8,35 @@ dashedName: remove-items-using-splice
# --description--
Ok, so we've learned how to remove elements from the beginning and end of arrays using `shift()` and `pop()`, but what if we want to remove an element from somewhere in the middle? Or remove more than one element at once? Well, that's where `splice()` comes in. `splice()` allows us to do just that: **remove any number of consecutive elements** from anywhere in an array.
在之前的挑战中,我们已经学习了如何用 `shift()` `pop()` 从数组的开头或末尾移除元素。 但如果我们想删除数组中间的一个元素, 或者想一次删除多个元素,该如何操作呢? 这时候我们就需要使用 `splice()` 方法了, `splice()` 可以让我们从数组中的任意位置**连续删除任意数量的元素**。
`splice()` can take up to 3 parameters, but for now, we'll focus on just the first 2. The first two parameters of `splice()` are integers which represent indexes, or positions, of the array that `splice()` is being called upon. And remember, arrays are *zero-indexed*, so to indicate the first element of an array, we would use `0`. `splice()`'s first parameter represents the index on the array from which to begin removing elements, while the second parameter indicates the number of elements to delete. For example:
`splice()` 最多可以接受 3 个参数,但现在我们先关注前两个。 `splice()` 接收的前两个参数是整数,表示正在调用 的`splice()` 数组中的元素的索引或位置。 别忘了,数组的索引是*从 0 开始的*,所以我们要用 `0` 来表示数组中的第一个元素。 `splice()` 的第一个参数代表从数组中的哪个索引开始移除元素,而第二个参数表示要从数组中的这个位置开始删除多少个元素。 例如:
```js
let array = ['today', 'was', 'not', 'so', 'great'];
array.splice(2, 2);
// remove 2 elements beginning with the 3rd element
// array now equals ['today', 'was', 'great']
```
`splice()` not only modifies the array it's being called on, but it also returns a new array containing the value of the removed elements:
这里我们移除 2 个元素,首先是第三个元素(索引为 2`array` 会有值 `['today', 'was', 'great']`
`splice()` 不仅会修改调用该方法的数组,还会返回一个包含被移除元素的数组:
```js
let array = ['I', 'am', 'feeling', 'really', 'happy'];
let newArray = array.splice(3, 2);
// newArray equals ['really', 'happy']
```
`newArray` 值为 `['really', 'happy']`
# --instructions--
We've initialized an array `arr`. Use `splice()` to remove elements from `arr`, so that it only contains elements that sum to the value of `10`.
我们已经定义了数组 `arr`。 请使用 `splice()` `arr` 里移除元素,使剩余的元素之和为 `10`
# --hints--
You should not change the original line of `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`.
不应修改这一行 `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`
```js
assert(
@ -43,7 +44,7 @@ assert(
);
```
`arr` should only contain elements that sum to `10`.
`arr` 的剩余元素之和应为 `10`
```js
assert.strictEqual(
@ -52,13 +53,13 @@ assert.strictEqual(
);
```
Your code should utilize the `splice()` method on `arr`.
应对 `arr` 调用 `splice()` 方法。
```js
assert(__helpers.removeWhiteSpace(code).match(/arr\.splice\(/));
```
The splice should only remove elements from `arr` and not add any additional elements to `arr`.
splice 应只删除 `arr` 里面的元素,不能给 `arr` 添加元素。
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b7e367417b2b2512b20
title: Use an Array to Store a Collection of Data
title: 使用数组存储不同类型的数据
challengeType: 1
forumTopicId: 301167
dashedName: use-an-array-to-store-a-collection-of-data
@ -8,15 +8,16 @@ dashedName: use-an-array-to-store-a-collection-of-data
# --description--
The below is an example of the simplest implementation of an array data structure. This is known as a <dfn>one-dimensional array</dfn>, meaning it only has one level, or that it does not have any other arrays nested within it. Notice it contains <dfn>booleans</dfn>, <dfn>strings</dfn>, and <dfn>numbers</dfn>, among other valid JavaScript data types:
以下是最简单的数组Array示例 这是一个一维数组(<dfn>one-dimensional array</dfn>),它只有一层,或者说它里面没有包含其它数组。 可以观察到,这个数组中只包含了布尔值(<dfn>booleans</dfn>)、字符串(<dfn>strings</dfn>)、数字(<dfn>numbers</dfn>)以及 JavaScript 中的其他数据类型:
```js
let simpleArray = ['one', 2, 'three', true, false, undefined, null];
console.log(simpleArray.length);
// logs 7
```
All arrays have a length property, which as shown above, can be very easily accessed with the syntax `Array.length`. A more complex implementation of an array can be seen below. This is known as a <dfn>multi-dimensional array</dfn>, or an array that contains other arrays. Notice that this array also contains JavaScript <dfn>objects</dfn>, which we will examine very closely in our next section, but for now, all you need to know is that arrays are also capable of storing complex objects.
调用 `console.log` 显示 `7`
所有数组都有一个表示长度的属性,我们可以通过 `Array.length` 来访问它。 下面是一个关于数组的更复杂的例子。 这是一个多维数组 <dfn>multi-dimensional Array</dfn>),或者说是一个包含了其他数组的数组。 可以注意到,在它的内部还包含了 JavaScript 中的对象(<dfn>objects</dfn>)结构。 我们会在后面的小节中讨论该数据结构,但现在你只需要知道数组能够存储复杂的对象类型数据。
```js
let complexArray = [
@ -45,35 +46,35 @@ let complexArray = [
# --instructions--
We have defined a variable called `yourArray`. Complete the statement by assigning an array of at least 5 elements in length to the `yourArray` variable. Your array should contain at least one <dfn>string</dfn>, one <dfn>number</dfn>, and one <dfn>boolean</dfn>.
我们已经定义了一个名为 `yourArray` 的变量。 请修改代码,将一个含有至少 5 个元素的数组赋值给 `yourArray` 变量。 你的数组中应包含至少一个 <dfn>string</dfn> 类型的数据、一个 <dfn>number</dfn> 类型的数据和一个 <dfn>boolean</dfn> 类型的数据。
# --hints--
`yourArray` should be an array.
`yourArray` 应为数组。
```js
assert.strictEqual(Array.isArray(yourArray), true);
```
`yourArray` should be at least 5 elements long.
`yourArray` 应包含至少 5 个元素。
```js
assert.isAtLeast(yourArray.length, 5);
```
`yourArray` should contain at least one `boolean`.
`yourArray` 应包含至少一个 `boolean`
```js
assert(yourArray.filter((el) => typeof el === 'boolean').length >= 1);
```
`yourArray` should contain at least one `number`.
`yourArray` 应包含至少一个 `number`
```js
assert(yourArray.filter((el) => typeof el === 'number').length >= 1);
```
`yourArray` should contain at least one `string`.
`yourArray` 应包含至少一个 `string`
```js
assert(yourArray.filter((el) => typeof el === 'string').length >= 1);

View File

@ -1,6 +1,6 @@
---
id: 56bbb991ad1ed5201cd392ca
title: Access Array Data with Indexes
title: 通过索引访问数组中的数据
challengeType: 1
videoUrl: 'https://scrimba.com/c/cBZQbTz'
forumTopicId: 16158
@ -9,30 +9,31 @@ dashedName: access-array-data-with-indexes
# --description--
We can access the data inside arrays using <dfn>indexes</dfn>.
我们可以使用索引(<dfn>indexes</dfn>)来访问数组中的数据。
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`.
数组索引与字符串一样使用方括号来表示,不同的是,它们不是指定字符,而是指定数组中的一个条目。 数组索引与字符串索引一样是从 0 开始(<dfn>zero-based</dfn>)的,所以数组中第一个元素的索引编号是 `0`
<br>
**Example**
**示例**
```js
var array = [50,60,70];
array[0]; // equals 50
var data = array[1]; // equals 60
array[0];
var data = array[1];
```
**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.
现在 `array[0]` 的值是 `50` `data` 的值为 `60`.
**注意:**数组名与方括号之间不应该有任何空格,比如`array [0]` 。 尽管 JavaScript 能够正确处理这种情况,但是当其他程序员阅读你写的代码时,这可能让他们感到困惑。
# --instructions--
Create a variable called `myData` and set it to equal the first value of `myArray` using bracket notation.
创建一个名为 `myData` 的变量,使用方括号取出 `myArray` 数组中第一个元素的值并将其赋值给新创建的变量。
# --hints--
The variable `myData` should equal the first value of `myArray`.
变量 `myData` 应该等于`myArray` 数组中第一个元素的值。
```js
assert(
@ -50,7 +51,7 @@ assert(
);
```
The data in variable `myArray` should be accessed using bracket notation.
应该使用括号访问变量 `myArray` 中的数据。
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56592a60ddddeae28f7aa8e1
title: Access Multi-Dimensional Arrays With Indexes
title: 使用索引访问多维数组
challengeType: 1
videoUrl: 'https://scrimba.com/c/ckND4Cq'
forumTopicId: 16159
@ -9,9 +9,9 @@ dashedName: access-multi-dimensional-arrays-with-indexes
# --description--
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.
我们可以把<dfn>多维</dfn>数组看作成是*数组中的数组*。 使用方括号表示法访问数组时,第一个方括号访问的是数组的最外层(第一层),第二个方括号访问的是数组的第二层,以此类推。
**Example**
**例如:**
```js
var arr = [
@ -20,27 +20,28 @@ var arr = [
[7,8,9],
[[10,11,12], 13, 14]
];
arr[3]; // equals [[10,11,12], 13, 14]
arr[3][0]; // equals [10,11,12]
arr[3][0][1]; // equals 11
arr[3];
arr[3][0];
arr[3][0][1];
```
**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.
`arr[3]``[[10, 11, 12], 13, 14]``arr[3][0]``[10, 11, 12]`,并且 `arr[3][0][1]``11`
**注意:** 数组名与方括号之间不应该有任何空格,比如`array [0][0]` 甚至是 `array [0] [0]` 都是不允许的。 尽管 JavaScript 能够正确处理这种情况,但是当其他程序员阅读你写的代码时,这可能让他们感到困惑。
# --instructions--
Using bracket notation select an element from `myArray` such that `myData` is equal to `8`.
使用方括号从 `myArray` 中选取一个值,使得 `myData` 等于 `8`
# --hints--
`myData` should be equal to `8`.
`myData` 应该等于 `8`
```js
assert(myData === 8);
```
You should be using bracket notation to read the correct value from `myArray`.
你应该使用方括号从 `myArray` 中读取正确的值。
```js
assert(/myData=myArray\[2\]\[1\]/.test(__helpers.removeWhiteSpace(code)));

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244cd
title: Accessing Nested Arrays
title: 访问嵌套数组
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 = [
@ -32,23 +32,25 @@ var ourPets = [
]
}
];
ourPets[0].names[1]; // "Fluffy"
ourPets[1].names[0]; // "Spot"
ourPets[0].names[1];
ourPets[1].names[0];
```
`ourPets[0].names[1]` 应该是字符串 `Fluffy` 并且 `ourPets[1].names[0]` 应该是字符串 `Spot`
# --instructions--
Retrieve the second tree from the variable `myPlants` using object dot and array bracket notation.
使用对象的点号和数组的方括号从变量 `myPlants` 检索出第二棵树。
# --hints--
`secondTree` should equal "pine".
`secondTree` 应该等于字符串 `pine`
```js
assert(secondTree === 'pine');
```
Your code should use dot and bracket notation to access `myPlants`.
你的代码应该使用点号和方括号访问 `myPlants`
```js
assert(/=\s*myPlants\[1\].list\[1\]/.test(code));

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244cc
title: Accessing Nested Objects
title: 访问嵌套对象
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 = {
@ -26,23 +26,25 @@ var ourStorage = {
"bottom drawer": "soda"
}
};
ourStorage.cabinet["top drawer"].folder2; // "secrets"
ourStorage.desk.drawer; // "stapler"
ourStorage.cabinet["top drawer"].folder2;
ourStorage.desk.drawer;
```
`ourStorage.cabinet["top drawer"].folder2` 将会是字符串 `secrets`,并且 `ourStorage.desk.drawer` 将会是字符串 `stapler`
# --instructions--
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.
访问 `myStorage` 对象并将 `glove box` 属性的内容赋值给 `gloveBoxContents` 变量。 在可能的情况下,对所有的属性使用点号,否则使用方括号。
# --hints--
`gloveBoxContents` should equal "maps".
`gloveBoxContents` 应该等于字符串 `maps`
```js
assert(gloveBoxContents === 'maps');
```
Your code should use dot and bracket notation to access `myStorage`.
你的代码应该使用点号和方括号来访问 `myStorage`
```js
assert(/=\s*myStorage\.car\.inside\[\s*("|')glove box\1\s*\]/g.test(code));

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244c8
title: Accessing Object Properties with Bracket Notation
title: 使用方括号表示法访问对象属性
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 = {
@ -21,44 +21,46 @@ var myObj = {
"More Space": "Spock",
"NoSpace": "USS Enterprise"
};
myObj["Space Name"]; // Kirk
myObj['More Space']; // Spock
myObj["NoSpace"]; // USS Enterprise
myObj["Space Name"];
myObj['More Space'];
myObj["NoSpace"];
```
Note that property names with spaces in them must be in quotes (single or double).
`myObj["Space Name"]` 将会是字符串 `Kirk``myObj['More Space']` 将会是字符串 `Spock`,并且`myObj["NoSpace"]` 将会是字符串 `USS Enterprise`
注意,如果属性名中包含空格,就必须使用引号(单引号或双引号)将它们包裹起来。
# --instructions--
Read the values of the properties `"an entree"` and `"the drink"` of `testObj` using bracket notation and assign them to `entreeValue` and `drinkValue` respectively.
使用方括号读取 `testObj` `an entree` `the drink` 的属性值,并分别将它们赋值给 `entreeValue` `drinkValue`
# --hints--
`entreeValue` should be a string
`entreeValue` 应该是一个字符串。
```js
assert(typeof entreeValue === 'string');
```
The value of `entreeValue` should be `"hamburger"`
`entreeValue` 的值应该为字符串 `hamburger`
```js
assert(entreeValue === 'hamburger');
```
`drinkValue` should be a string
`drinkValue` 应该是一个字符串
```js
assert(typeof drinkValue === 'string');
```
The value of `drinkValue` should be `"water"`
`drinkValue` 的值应该为字符串 `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: Accessing Object Properties with Dot Notation
title: 通过点号表示法访问对象属性
challengeType: 1
videoUrl: 'https://scrimba.com/c/cGryJs8'
forumTopicId: 16164
@ -9,52 +9,53 @@ 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 = {
prop1: "val1",
prop2: "val2"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2
var prop1val = myObj.prop1;
var prop2val = myObj.prop2;
```
`prop1val` 的值将为字符串 `val1`,并且`prop2val` 的值将为字符串 `val2`
# --instructions--
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`.
使用点号读取 `testObj` 的属性值。 将变量 `hatValue` 的值设置为该对象的 `hat` 属性的值,并将变量 `shirtValue` 的值设置为该对象的 `shirt` 属性的值。
# --hints--
`hatValue` should be a string
`hatValue` 应该是一个字符串
```js
assert(typeof hatValue === 'string');
```
The value of `hatValue` should be `"ballcap"`
`hatValue` 的值应该为字符串 `ballcap`
```js
assert(hatValue === 'ballcap');
```
`shirtValue` should be a string
`shirtValue` 应该是一个字符串
```js
assert(typeof shirtValue === 'string');
```
The value of `shirtValue` should be `"jersey"`
`shirtValue` 的值应该为字符串 `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: Accessing Object Properties with Variables
title: 通过变量访问对象属性
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 = {
@ -19,10 +19,12 @@ var dogs = {
};
var myDog = "Hunter";
var myBreed = dogs[myDog];
console.log(myBreed); // "Doberman"
console.log(myBreed);
```
Another way you can use this concept is when the property's name is collected dynamically during the program execution, as follows:
字符串 `Doberman` 将会出现在控制台中。
使用这一概念的另一种情况是:属性的名字是在程序运行期间动态收集得到的。如下所示:
```js
var someObj = {
@ -32,49 +34,51 @@ function propPrefix(str) {
var s = "prop";
return s + str;
}
var someProp = propPrefix("Name"); // someProp now holds the value 'propName'
console.log(someObj[someProp]); // "John"
var someProp = propPrefix("Name");
console.log(someObj[someProp]);
```
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*.
`someProp` 的值将为字符串 `propName`,并且字符串 `John` 将会出现在控制台中。
注意,当使用变量名访问属性时,我们*没有*使用引号包裹它,因为我们正在使用的是变量的*值*,而不是变量的*名字*。
# --instructions--
Set the `playerNumber` variable to `16`. Then, use the variable to look up the player's name and assign it to `player`.
将变量 `playerNumber` 设置为 `16`。 然后,使用该变量查找玩家的名字,并将其赋值给`player`
# --hints--
`playerNumber` should be a number
`playerNumber` 应该是一个数字
```js
assert(typeof playerNumber === 'number');
```
The variable `player` should be a string
变量 `player` 应该是一个字符串
```js
assert(typeof player === 'string');
```
The value of `player` should be "Montana"
`player` 的值应该为字符串 `Montana`
```js
assert(player === 'Montana');
```
You should use bracket notation to access `testObj`
你应该使用方括号访问 `testObj`
```js
assert(/testObj\s*?\[.*?\]/.test(code));
```
You should not assign the value `Montana` to the variable `player` directly.
你不应该直接将值 `Montana` 赋给变量 `player`
```js
assert(!code.match(/player\s*=\s*"|\'\s*Montana\s*"|\'\s*;/gi));
```
You should be using the variable `playerNumber` in your bracket notation
你应该在你的方括号内使用变量 `playerNumber`
```js
assert(/testObj\s*?\[\s*playerNumber\s*\]/.test(code));

View File

@ -1,6 +1,6 @@
---
id: 56bbb991ad1ed5201cd392d2
title: Add New Properties to a JavaScript Object
title: JavaScript 对象添加新属性
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.
你也可以像更改属性一样给 JavaScript 对象添加属性。
Here's how we would add a `"bark"` property to `ourDog`:
这里展示了如何给 `ourDog` 添加一个属性 `bark`
`ourDog.bark = "bow-wow";`
or
或者
`ourDog["bark"] = "bow-wow";`
Now when we evaluate `ourDog.bark`, we'll get his bark, "bow-wow".
现在,当我们执行 `ourDog.bark` 时,我们就能得到他的叫声,`bow-wow`
Example:
例如:
```js
var ourDog = {
@ -36,17 +36,17 @@ ourDog.bark = "bow-wow";
# --instructions--
Add a `"bark"` property to `myDog` and set it to a dog sound, such as "woof". You may use either dot or bracket notation.
`myDog` 添加一个属性 `bark` ,并将其设置为狗的声音,比如“woof. 你可以使用点号表示法或方括号表示法来完成此挑战。
# --hints--
You should add the property `"bark"` to `myDog`.
你应该将属性 `bark` 添加到 `myDog`
```js
assert(myDog.bark !== undefined);
```
You should not add `"bark"` to the setup section.
你不应该在 Setup 部分添加 `bark`
```js
assert(!/bark[^\n]:/.test(code));

View File

@ -1,6 +1,6 @@
---
id: cf1111c1c11feddfaeb3bdef
title: Add Two Numbers with JavaScript
title: 加法运算
challengeType: 1
videoUrl: 'https://scrimba.com/c/cM2KBAG'
forumTopicId: 16650
@ -9,31 +9,33 @@ dashedName: add-two-numbers-with-javascript
# --description--
`Number` is a data type in JavaScript which represents numeric data.
`Number` 是 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.
JavaScript 中,我们通过符号 `+` 来进行加法运算。
**Example:**
**代码示例:**
```js
myVar = 5 + 10; // assigned 15
myVar = 5 + 10;
```
现在,变量 `myVar` 的值为 `15`
# --instructions--
Change the `0` so that sum will equal `20`.
请改变数字 `0` 让变量 sum 的值为 `20`
# --hints--
`sum` should equal `20`.
`sum` 的值应该等于 `20`
```js
assert(sum === 20);
```
You should use the `+` operator.
请使用 `+` 运算符。
```js
assert(/\+/.test(code));

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244de
title: Adding a Default Option in Switch Statements
title: 在 switch 语句中添加默认选项
challengeType: 1
videoUrl: 'https://scrimba.com/c/c3JvVfg'
forumTopicId: 16653
@ -9,9 +9,9 @@ dashedName: adding-a-default-option-in-switch-statements
# --description--
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.
`switch` 语句中,你可能无法用 `case` 枚举出所有可能的值。 相反,你可以添加 `default` 语句,它会在找不到相匹配的 `case` 语句之后执行。 你可以把它看作是 `if/else` 链中最后的那个 `else` 语句。
A `default` statement should be the last case.
`default` 语句应该被放到最后。
```js
switch (num) {
@ -30,57 +30,57 @@ switch (num) {
# --instructions--
Write a switch statement to set `answer` for the following conditions:
`"a"` - "apple"
`"b"` - "bird"
`"c"` - "cat"
`default` - "stuff"
写一个 switch 语句,设置以下条件设置 `answer`
`a` - `apple`
`b` - `bird`
`c` - `cat`
`default` - `stuff`
# --hints--
`switchOfStuff("a")` should have a value of "apple"
`switchOfStuff("a")` 应该返回字符串 `apple`
```js
assert(switchOfStuff('a') === 'apple');
```
`switchOfStuff("b")` should have a value of "bird"
`switchOfStuff("b")` 应该返回字符串 `bird`
```js
assert(switchOfStuff('b') === 'bird');
```
`switchOfStuff("c")` should have a value of "cat"
`switchOfStuff("c")` 应该返回字符串 `cat`
```js
assert(switchOfStuff('c') === 'cat');
```
`switchOfStuff("d")` should have a value of "stuff"
`switchOfStuff("d")` 应该返回字符串 `stuff`
```js
assert(switchOfStuff('d') === 'stuff');
```
`switchOfStuff(4)` should have a value of "stuff"
`switchOfStuff(4)` 应该返回字符串 `stuff`
```js
assert(switchOfStuff(4) === 'stuff');
```
You should not use any `if` or `else` statements
不能使用 `if` `else` 语句。
```js
assert(!/else/g.test(code) || !/if/g.test(code));
```
You should use a `default` statement
你应该使用 `default` 语句。
```js
assert(switchOfStuff('string-to-trigger-default-case') === 'stuff');
```
You should have at least 3 `break` statements
你至少应该写 3 个 `break` 语句。
```js
assert(code.match(/break/g).length > 2);

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244ed
title: Appending Variables to Strings
title: 将变量追加到字符串
challengeType: 1
videoUrl: 'https://scrimba.com/c/cbQmZfa'
forumTopicId: 16656
@ -9,30 +9,31 @@ dashedName: appending-variables-to-strings
# --description--
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.
就像我们可以用多行字符串<dfn>字面量</dfn>构建单个字符串一样,我们还可以使用加且赋值(`+=`)运算符将字符串追加到字符串的末尾。
Example:
示例:
```js
var anAdjective = "awesome!";
var ourStr = "freeCodeCamp is ";
ourStr += anAdjective;
// ourStr is now "freeCodeCamp is awesome!"
```
`ourStr` 值为 `freeCodeCamp is awesome!`
# --instructions--
Set `someAdjective` to a string of at least 3 characters and append it to `myStr` using the `+=` operator.
`someAdjective` 设置为一个至少包含 3 个字符的字符串,然后使用 `+=` 运算符将它追加到 `myStr`
# --hints--
`someAdjective` should be set to a string at least 3 characters long.
`someAdjective` 应当为包含至少三个字符的字符串。
```js
assert(typeof someAdjective !== 'undefined' && someAdjective.length > 2);
```
You should append `someAdjective` to `myStr` using the `+=` operator.
你应该使用 `+=` 运算符将 `someAdjective` 追加到 `myStr`
```js
assert(code.match(/myStr\s*\+=\s*someAdjective\s*/).length > 0);

View File

@ -1,6 +1,6 @@
---
id: 5ee127a03c3b35dd45426493
title: Assigning the Value of One Variable to Another
title: 将一个变量的值赋给另一个
challengeType: 1
videoUrl: ''
forumTopicId: 418265
@ -9,7 +9,7 @@ dashedName: assigning-the-value-of-one-variable-to-another
# --description--
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.
在使用<dfn>赋值</dfn>运算符赋予变量某个值后,你可以使用<dfn>赋值</dfn>运算符将该变量的值赋给另一个变量。
```js
var myVar;
@ -18,27 +18,27 @@ var myNum;
myNum = myVar;
```
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`.
以上代码声明了一个没有初始值的变量 `myVar`,然后给它赋值为 `5`。 紧接着,又声明了一个没有初始值的变量 `myNum`。 然后,变量 `myVar` 的内容(也就是 `5`)被赋给了变量 `myNum`。 现在,变量 `myNum` 的值也为 `5`
# --instructions--
Assign the contents of `a` to variable `b`.
把变量 `a` 的内容赋给变量 `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` should have a value of 7.
`b` 的值应该为 `7`
```js
assert(typeof b === 'number' && b === 7);
```
`a` should be assigned to `b` with `=`.
应该使用 `=` `a` 赋给 `b`
```js
assert(/b\s*=\s*a\s*/g.test(code));

View File

@ -1,6 +1,6 @@
---
id: 56bbb991ad1ed5201cd392d0
title: Build JavaScript Objects
title: 创建 JavaScript 对象
challengeType: 1
videoUrl: 'https://scrimba.com/c/cWGkbtd'
forumTopicId: 16769
@ -9,13 +9,13 @@ dashedName: build-javascript-objects
# --description--
You may have heard the term `object` before.
你之前可能听过 `object` 这个词。
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`.
对象和 `arrays` 类似,区别在于数组使用索引来访问和修改数据,而对象中的数据是通过 `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 = {
};
```
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:
在这个示例中,所有的属性都被纯属为字符串,比如 `name``legs` `tails`。 然而,你也可以使用数字作为属性。 你甚至可以省略单字字符串属性中的引号,如下所示:
```js
var anotherObject = {
@ -36,17 +36,17 @@ var anotherObject = {
};
```
However, if your object has any non-string properties, JavaScript will automatically typecast them as strings.
然而如果你的对象有非字符串属性的话JavaScript 会自动将它们转为字符串。
# --instructions--
Make an object that represents a dog called `myDog` which contains the properties `"name"` (a string), `"legs"`, `"tails"` and `"friends"`.
确保对象表示一只名为 `myDog` 的狗,包含属性 `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.
你可以随意设置这些对象的属性值,只要 `name` 是字符串,`legs` `tails` 是数字,`friends` 是数组即可。
# --hints--
`myDog` should contain the property `name` and it should be a `string`.
`myDog` 应该包含 `name` 属性,并且它应该是一个 `string`
```js
assert(
@ -64,7 +64,7 @@ assert(
);
```
`myDog` should contain the property `legs` and it should be a `number`.
`myDog`应该包含 `legs` 属性,并且它应该是一个 `number`
```js
assert(
@ -82,7 +82,7 @@ assert(
);
```
`myDog` should contain the property `tails` and it should be a `number`.
`myDog` 应该包含 `tails` 属性,并且它应该是一个 `number`
```js
assert(
@ -100,7 +100,7 @@ assert(
);
```
`myDog` should contain the property `friends` and it should be an `array`.
`myDog` 应该包含 `friends` 属性,并且它应该是一个 `array`
```js
assert(
@ -118,7 +118,7 @@ assert(
);
```
`myDog` should only contain all the given properties.
`myDog` 只应该包含所有给定的属性。
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244dc
title: Chaining If Else Statements
title: 多个 if else 语句
challengeType: 1
videoUrl: 'https://scrimba.com/c/caeJgsw'
forumTopicId: 16772
@ -9,7 +9,7 @@ dashedName: chaining-if-else-statements
# --description--
`if/else` statements can be chained together for complex logic. Here is <dfn>pseudocode</dfn> of multiple chained `if` / `else if` statements:
`if/else` 语句串联在一起可以实现复杂的逻辑。 这是多个 `if` / `else if` 语句串联在一起的<dfn>伪代码</dfn>
```js
if (condition1) {
@ -26,89 +26,89 @@ if (condition1) {
# --instructions--
Write chained `if`/`else if` statements to fulfill the following conditions:
请将 `if`/`else if` 语句串联起来,实现下面的逻辑:
`num < 5` - return "Tiny"
`num < 10` - return "Small"
`num < 15` - return "Medium"
`num < 20` - return "Large"
`num >= 20` - return "Huge"
`num < 5` - 返回 `Tiny`
`num < 10` - 返回 `Small`
`num < 15` - 返回 `Medium`
`num < 20` - 返回 `Large`
`num >= 20` - 返回 `Huge`
# --hints--
You should have at least four `else` statements
应至少有 4 个 `else` 语句。
```js
assert(code.match(/else/g).length > 3);
```
You should have at least four `if` statements
应至少有 4 个 `if` 语句。
```js
assert(code.match(/if/g).length > 3);
```
You should have at least one `return` statement
应至少有 1 个 `return` 语句。
```js
assert(code.match(/return/g).length >= 1);
```
`testSize(0)` should return "Tiny"
`testSize(0)` 应该返回字符串 `Tiny`
```js
assert(testSize(0) === 'Tiny');
```
`testSize(4)` should return "Tiny"
`testSize(4)` 应该返回字符串 `Tiny`
```js
assert(testSize(4) === 'Tiny');
```
`testSize(5)` should return "Small"
`testSize(5)` 应该返回字符串 `Small`
```js
assert(testSize(5) === 'Small');
```
`testSize(8)` should return "Small"
`testSize(8)` 应该返回字符串 `Small`
```js
assert(testSize(8) === 'Small');
```
`testSize(10)` should return "Medium"
`testSize(10)` 应该返回字符串 `Medium`
```js
assert(testSize(10) === 'Medium');
```
`testSize(14)` should return "Medium"
`testSize(14)` 应该返回字符串 `Medium`
```js
assert(testSize(14) === 'Medium');
```
`testSize(15)` should return "Large"
`testSize(15)` 应该返回字符串 `Large`
```js
assert(testSize(15) === 'Large');
```
`testSize(17)` should return "Large"
`testSize(17)` 应该返回字符串 `Large`
```js
assert(testSize(17) === 'Large');
```
`testSize(20)` should return "Huge"
`testSize(20)` 应该返回字符串 `Huge`
```js
assert(testSize(20) === 'Huge');
```
`testSize(25)` should return "Huge"
`testSize(25)` 应该返回字符串 `Huge`
```js
assert(testSize(25) === 'Huge');

View File

@ -1,6 +1,6 @@
---
id: bd7123c9c441eddfaeb4bdef
title: Comment Your JavaScript Code
title: 给代码添加注释
challengeType: 1
videoUrl: 'https://scrimba.com/c/c7ynnTp'
forumTopicId: 16783
@ -9,39 +9,38 @@ dashedName: comment-your-javascript-code
# --description--
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:
JavaScript有两种写注释的方法。
Using `//` will tell JavaScript to ignore the remainder of the text on the current line:
使用 `//` 注释掉当前行的代码。 这是一个行内注释:
```js
// This is an in-line comment.
```
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--
You should create a `//` style comment that contains at least five letters.
创建一个 `//` 样式的注释,被注释的文本至少要包含 5 个字符。
```js
assert(code.match(/(\/\/)...../g));
```
You should create a `/* */` style comment that contains at least five letters.
创建一个 `/* */` 样式的注释,被注释的文本至少要包含 5 个字符。
```js
assert(code.match(/(\/\*)([^\/]{5,})(?=\*\/)/gm));
@ -50,7 +49,9 @@ assert(code.match(/(\/\*)([^\/]{5,})(?=\*\/)/gm));
# --seed--
## --seed-contents--
```js
```
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244d0
title: Comparison with the Equality Operator
title: 相等运算符
challengeType: 1
videoUrl: 'https://scrimba.com/c/cKyVMAL'
forumTopicId: 16784
@ -9,9 +9,9 @@ dashedName: comparison-with-the-equality-operator
# --description--
There are many <dfn>comparison operators</dfn> in JavaScript. All of these operators return a boolean `true` or `false` value.
在 JavaScript 中,有很多 <dfn>相互比较的操作</dfn>。 所有这些操作符都返回一个 `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.
最基本的运算符是相等运算符:`==`。 相等运算符比较两个值,如果它们是相等,返回 `true`,如果它们不相等,返回 `false`。 值得注意的是相等运算符不同于赋值运算符(`=`),赋值运算符是把等号右边的值赋给左边的变量。
```js
function equalityTest(myVal) {
@ -22,40 +22,42 @@ function equalityTest(myVal) {
}
```
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:
如果 `myVal` 等于 `10`,相等运算符会返回 `true`,因此大括号里面的代码会被执行,函数将返回 `Equal`。 否则,函数返回 `Not Equal`。 在 JavaScript 中,为了让两个不同的<dfn>数据类型</dfn>(例如 `numbers` `strings`)的值可以作比较,它必须把一种类型转换为另一种类型。 这叫作 “类型强制转换”。 转换之后,可以像下面这样来比较:
```js
1 == 1 // true
1 == 2 // false
1 == '1' // true
"3" == 3 // true
1 == 1
1 == 2
1 == '1'
"3" == 3
```
按顺序,这些表达式会返回 `true``false``true``true`
# --instructions--
Add the equality operator to the indicated line so that the function will return "Equal" when `val` is equivalent to `12`.
把相等运算符添加到指定的行,这样当 `val` 的值为 `12` 的时候,函数会返回 `Equal`
# --hints--
`testEqual(10)` should return "Not Equal"
`testEqual(10)` 应该返回字符串 `Not Equal`
```js
assert(testEqual(10) === 'Not Equal');
```
`testEqual(12)` should return "Equal"
`testEqual(12)` 应该返回字符串 `Equal`
```js
assert(testEqual(12) === 'Equal');
```
`testEqual("12")` should return "Equal"
`testEqual("12")` 应该返回字符串 `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: 56533eb9ac21ba0edf2244d5
title: Comparison with the Greater Than Or Equal To Operator
title: 大于或等于运算符
challengeType: 1
videoUrl: 'https://scrimba.com/c/c6KBqtV'
forumTopicId: 16785
@ -9,68 +9,70 @@ dashedName: comparison-with-the-greater-than-or-equal-to-operator
# --description--
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`.
使用大于等于运算符(`>=`)来比较两个数字的大小。 如果大于等于运算符左边的数字比右边的数字大或者相等,会返回 `true`。 否则,会返回 `false`
Like the equality operator, `greater than or equal to` operator will convert data types while comparing.
与相等运算符相似,大于等于运算符在比较的时候会转换值的数据类型。
**Examples**
**例如:**
```js
6 >= 6 // true
7 >= '3' // true
2 >= 3 // false
'7' >= 9 // false
6 >= 6
7 >= '3'
2 >= 3
'7' >= 9
```
按顺序,这些表达式会返回 `true``true``false``false`
# --instructions--
Add the greater than or equal to operator to the indicated lines so that the return statements make sense.
添加大于等于运算符到指定行,使得函数的返回语句有意义。
# --hints--
`testGreaterOrEqual(0)` should return "Less than 10"
`testGreaterOrEqual(0)` 应该返回字符串 `Less than 10`
```js
assert(testGreaterOrEqual(0) === 'Less than 10');
```
`testGreaterOrEqual(9)` should return "Less than 10"
`testGreaterOrEqual(9)` 应该返回字符串 `Less than 10`
```js
assert(testGreaterOrEqual(9) === 'Less than 10');
```
`testGreaterOrEqual(10)` should return "10 or Over"
`testGreaterOrEqual(10)` 应该返回字符串 `10 or Over`
```js
assert(testGreaterOrEqual(10) === '10 or Over');
```
`testGreaterOrEqual(11)` should return "10 or Over"
`testGreaterOrEqual(11)` 应该返回字符串 `10 or Over`
```js
assert(testGreaterOrEqual(11) === '10 or Over');
```
`testGreaterOrEqual(19)` should return "10 or Over"
`testGreaterOrEqual(19)` 应该返回字符串 `10 or Over`
```js
assert(testGreaterOrEqual(19) === '10 or Over');
```
`testGreaterOrEqual(100)` should return "20 or Over"
`testGreaterOrEqual(100)` 应该返回字符串 `20 or Over`
```js
assert(testGreaterOrEqual(100) === '20 or Over');
```
`testGreaterOrEqual(21)` should return "20 or Over"
`testGreaterOrEqual(21)` 应该返回字符串 `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: Comparison with the Inequality Operator
title: 不等运算符
challengeType: 1
videoUrl: 'https://scrimba.com/c/cdBm9Sr'
forumTopicId: 16787
@ -9,55 +9,57 @@ dashedName: comparison-with-the-inequality-operator
# --description--
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.
不相等运算符(`!=`)与相等运算符是相反的。 这意味着严格不相等并返回 `false` 的地方,用严格相等运算符会返回 `true`*反之亦然*。 与相等运算符类似,不相等运算符在比较的时候也会转换值的数据类型。
**Examples**
**例如**
```js
1 != 2 // true
1 != "1" // false
1 != '1' // false
1 != true // false
0 != false // false
1 != 2
1 != "1"
1 != '1'
1 != true
0 != false
```
按顺序,这些表达式会返回 `true``false``false``false``false`
# --instructions--
Add the inequality operator `!=` in the `if` statement so that the function will return "Not Equal" when `val` is not equivalent to `99`
`if` 语句中,添加不相等运算符 `!=`,这样函数在当 `val` 不等于 `99` 的时候,会返回 `Not Equal`
# --hints--
`testNotEqual(99)` should return "Equal"
`testNotEqual(99)` 应该返回字符串 `Equal`
```js
assert(testNotEqual(99) === 'Equal');
```
`testNotEqual("99")` should return "Equal"
`testNotEqual("99")` 应该返回字符串 `Equal`
```js
assert(testNotEqual('99') === 'Equal');
```
`testNotEqual(12)` should return "Not Equal"
`testNotEqual(12)` 应该返回字符串 `Not Equal`
```js
assert(testNotEqual(12) === 'Not Equal');
```
`testNotEqual("12")` should return "Not Equal"
`testNotEqual("12")` 应该返回字符串 `Not Equal`
```js
assert(testNotEqual('12') === 'Not Equal');
```
`testNotEqual("bob")` should return "Not Equal"
`testNotEqual("bob")` 应该返回字符串 `Not Equal`
```js
assert(testNotEqual('bob') === 'Not Equal');
```
You should use the `!=` operator
你应该使用 `!=` 运算符。
```js
assert(code.match(/(?!!==)!=/));

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244d7
title: Comparison with the Less Than Or Equal To Operator
title: 小于或等于运算符
challengeType: 1
videoUrl: 'https://scrimba.com/c/cNVR7Am'
forumTopicId: 16788
@ -9,67 +9,69 @@ dashedName: comparison-with-the-less-than-or-equal-to-operator
# --description--
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.
使用小于等于运算符(`<=`)比较两个数字的大小。 如果在小于等于运算符左边的数字小于或者等于右边的数字,它会返回 `true`。 如果在小于等于运算符左边的数字大于右边的数字,它会返回 `false`。 与相等运算符类似,小于或等于运算符会转换数据类型。
**Examples**
**例如**
```js
4 <= 5 // true
'7' <= 7 // true
5 <= 5 // true
3 <= 2 // false
'8' <= 4 // false
4 <= 5
'7' <= 7
5 <= 5
3 <= 2
'8' <= 4
```
按顺序,这些表达式会返回 `true``true``true``false``false`
# --instructions--
Add the less than or equal to operator to the indicated lines so that the return statements make sense.
添加小于等于运算符到指定行,使得函数的返回语句有意义。
# --hints--
`testLessOrEqual(0)` should return "Smaller Than or Equal to 12"
`testLessOrEqual(0)` 应该返回 `Smaller Than or Equal to 12`
```js
assert(testLessOrEqual(0) === 'Smaller Than or Equal to 12');
```
`testLessOrEqual(11)` should return "Smaller Than or Equal to 12"
`testLessOrEqual(11)` 应该返回 `Smaller Than or Equal to 12`
```js
assert(testLessOrEqual(11) === 'Smaller Than or Equal to 12');
```
`testLessOrEqual(12)` should return "Smaller Than or Equal to 12"
`testLessOrEqual(12)` 应该返回 `Smaller Than or Equal to 12`
```js
assert(testLessOrEqual(12) === 'Smaller Than or Equal to 12');
```
`testLessOrEqual(23)` should return "Smaller Than or Equal to 24"
`testLessOrEqual(23)` 应该返回 `Smaller Than or Equal to 24`
```js
assert(testLessOrEqual(23) === 'Smaller Than or Equal to 24');
```
`testLessOrEqual(24)` should return "Smaller Than or Equal to 24"
`testLessOrEqual(24)` 应该返回 `Smaller Than or Equal to 24`
```js
assert(testLessOrEqual(24) === 'Smaller Than or Equal to 24');
```
`testLessOrEqual(25)` should return "More Than 24"
`testLessOrEqual(25)` 应该返回 `More Than 24`
```js
assert(testLessOrEqual(25) === 'More Than 24');
```
`testLessOrEqual(55)` should return "More Than 24"
`testLessOrEqual(55)` 应该返回 `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: Comparison with the Strict Equality Operator
title: 严格相等运算符
challengeType: 1
videoUrl: 'https://scrimba.com/c/cy87atr'
forumTopicId: 16790
@ -9,44 +9,46 @@ 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.
严格相等运算符(`===`)是相对相等操作符(`==`)的另一种比较操作符。 与相等操作符转换数据两类型不同,严格相等运算符不会做类型转换。
If the values being compared have different types, they are considered unequal, and the strict equality operator will return false.
如果比较的值类型不同,那么在严格相等运算符比较下它们是不相等的,会返回 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.
这些条件将分别返回 `true` and `false`
在第二个例子中,`3` 是一个 `Number` 类型,而 `'3'` 是一个 `String` 类型。
# --instructions--
Use the strict equality operator in the `if` statement so the function will return "Equal" when `val` is strictly equal to `7`
`if` 语句中,添加不相等运算符,这样函数在当 `val` 严格等于 `7` 的时候,会返回 `Equal`
# --hints--
`testStrict(10)` should return "Not Equal"
`testStrict(10)` 应该返回字符串 `Not Equal`
```js
assert(testStrict(10) === 'Not Equal');
```
`testStrict(7)` should return "Equal"
`testStrict(7)` 应该返回字符串 `Equal`
```js
assert(testStrict(7) === 'Equal');
```
`testStrict("7")` should return "Not Equal"
`testStrict("7")` 应该返回字符串 `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: 56533eb9ac21ba0edf2244d8
title: Comparisons with the Logical And Operator
title: 逻辑与运算符
challengeType: 1
videoUrl: 'https://scrimba.com/c/cvbRVtr'
forumTopicId: 16799
@ -9,9 +9,9 @@ dashedName: comparisons-with-the-logical-and-operator
# --description--
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.
有时你需要在一次判断中做多个操作。 当且仅当<dfn>运算符</dfn>的左边和右边都是 true<dfn>逻辑与</dfn>运算符(`&&`)才会返回`true`
The same effect could be achieved by nesting an if statement inside another if:
同样的效果可以通过 if 语句的嵌套来实现:
```js
if (num > 5) {
@ -22,7 +22,7 @@ if (num > 5) {
return "No";
```
will only return "Yes" if `num` is greater than `5` and less than `10`. The same logic can be written as:
只有当 `num` 的值大于 `5` 并且小于`10` 时才会返回 `Yes`。 相同的逻辑可被写为:
```js
if (num > 5 && num < 10) {
@ -33,65 +33,65 @@ return "No";
# --instructions--
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"`.
请使用 `&&` 运算符把两个 if 语句合并为一个 if 语句,如果 `val` 小于或等于`50` 并且大于或等于 `25` 时,返回 `Yes`。 否则,将返回`No`
# --hints--
You should use the `&&` operator once
你应该使用 `&&` 运算符一次。
```js
assert(code.match(/&&/g).length === 1);
```
You should only have one `if` statement
你应该只有一个 `if` 表达式。
```js
assert(code.match(/if/g).length === 1);
```
`testLogicalAnd(0)` should return "No"
`testLogicalAnd(0)` 应该返回字符串 `No`
```js
assert(testLogicalAnd(0) === 'No');
```
`testLogicalAnd(24)` should return "No"
`testLogicalAnd(24)` 应该返回字符串 `No`
```js
assert(testLogicalAnd(24) === 'No');
```
`testLogicalAnd(25)` should return "Yes"
`testLogicalAnd(25)` 应该返回字符串 `Yes`
```js
assert(testLogicalAnd(25) === 'Yes');
```
`testLogicalAnd(30)` should return "Yes"
`testLogicalAnd(30)` 应该返回字符串 `Yes`
```js
assert(testLogicalAnd(30) === 'Yes');
```
`testLogicalAnd(50)` should return "Yes"
`testLogicalAnd(50)` 应该返回字符串 `Yes`
```js
assert(testLogicalAnd(50) === 'Yes');
```
`testLogicalAnd(51)` should return "No"
`testLogicalAnd(51)` 应该返回字符串 `No`
```js
assert(testLogicalAnd(51) === 'No');
```
`testLogicalAnd(75)` should return "No"
`testLogicalAnd(75)` 应该返回字符串 `No`
```js
assert(testLogicalAnd(75) === 'No');
```
`testLogicalAnd(80)` should return "No"
`testLogicalAnd(80)` 应该返回字符串 `No`
```js
assert(testLogicalAnd(80) === 'No');

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244d9
title: Comparisons with the Logical Or Operator
title: 逻辑或运算符
challengeType: 1
videoUrl: 'https://scrimba.com/c/cEPrGTN'
forumTopicId: 16800
@ -9,11 +9,11 @@ dashedName: comparisons-with-the-logical-or-operator
# --description--
The <dfn>logical or</dfn> operator (`||`) returns `true` if either of the <dfn>operands</dfn> is `true`. Otherwise, it returns `false`.
只要<dfn>逻辑或</dfn>运算符(`||`)两边的任何一个<dfn>运算</dfn>的结果是 `true`,则返回 `true`。 否则,返回 `false`
The <dfn>logical or</dfn> operator is composed of two pipe symbols: (`||`). This can typically be found between your Backspace and Enter keys.
<dfn>逻辑或</dfn>运算符由两个竖线(`||`)组成。 这个按键位于退格键和回车键之间。
The pattern below should look familiar from prior waypoints:
下面这样的语句你应该很熟悉:
```js
if (num > 10) {
@ -25,7 +25,7 @@ if (num < 5) {
return "Yes";
```
will return "Yes" only if `num` is between `5` and `10` (5 and 10 included). The same logic can be written as:
只有当 `num` 大于等于 `5` 或小于等于 `10` 时,函数才返回 `Yes`。 相同的逻辑可以简写成:
```js
if (num > 10 || num < 5) {
@ -36,65 +36,65 @@ return "Yes";
# --instructions--
Combine the two `if` statements into one statement which returns `"Outside"` if `val` is not between `10` and `20`, inclusive. Otherwise, return `"Inside"`.
请使用逻辑或运算符把两个 `if` 语句合并为一个语句,如果 `val` 不在 `10` `20` 之间(包括 10 和 20返回 `Outside`。 否则,返回 `Inside`
# --hints--
You should use the `||` operator once
应该使用一次 `||` 操作符。
```js
assert(code.match(/\|\|/g).length === 1);
```
You should only have one `if` statement
应该只有一个 `if` 表达式。
```js
assert(code.match(/if/g).length === 1);
```
`testLogicalOr(0)` should return "Outside"
`testLogicalOr(0)` 应该返回字符串 `Outside`
```js
assert(testLogicalOr(0) === 'Outside');
```
`testLogicalOr(9)` should return "Outside"
`testLogicalOr(9)` 应该返回字符串 `Outside`
```js
assert(testLogicalOr(9) === 'Outside');
```
`testLogicalOr(10)` should return "Inside"
`testLogicalOr(10)` 应该返回字符串 `Inside`
```js
assert(testLogicalOr(10) === 'Inside');
```
`testLogicalOr(15)` should return "Inside"
`testLogicalOr(15)` 应该返回字符串 `Inside`
```js
assert(testLogicalOr(15) === 'Inside');
```
`testLogicalOr(19)` should return "Inside"
`testLogicalOr(19)` 应该返回字符串 `Inside`
```js
assert(testLogicalOr(19) === 'Inside');
```
`testLogicalOr(20)` should return "Inside"
`testLogicalOr(20)` 应该返回字符串 `Inside`
```js
assert(testLogicalOr(20) === 'Inside');
```
`testLogicalOr(21)` should return "Outside"
`testLogicalOr(21)` 应该返回字符串 `Outside`
```js
assert(testLogicalOr(21) === 'Outside');
```
`testLogicalOr(25)` should return "Outside"
`testLogicalOr(25)` 应该返回字符串 `Outside`
```js
assert(testLogicalOr(25) === 'Outside');

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244af
title: Compound Assignment With Augmented Addition
title: 复合赋值之 +=
challengeType: 1
videoUrl: 'https://scrimba.com/c/cDR6LCb'
forumTopicId: 16661
@ -9,51 +9,53 @@ dashedName: compound-assignment-with-augmented-addition
# --description--
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:
在编程中,通常通过赋值来修改变量的内容。 记住,赋值时 JavaScript 会先计算等号右边的内容,所以我们可以写这样的语句:
`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.
`myVar` 加上 `5`。 以上是最常见的运算赋值语句,即先运算、再赋值。还有一类操作符是一步到位既做运算也赋值的。
One such operator is the `+=` operator.
其中一种就是 `+=` 运算符。
```js
var myVar = 1;
myVar += 5;
console.log(myVar); // Returns 6
console.log(myVar);
```
字符串 `6` 将会出现在控制台中。
# --instructions--
Convert the assignments for `a`, `b`, and `c` to use the `+=` operator.
使用 `+=` 操作符对 `a``b` `c` 实现同样的效果。
# --hints--
`a` should equal `15`.
`a` 应该等于 `15`
```js
assert(a === 15);
```
`b` should equal `26`.
`b` 应该等于 `26`
```js
assert(b === 26);
```
`c` should equal `19`.
`c` 应该等于 `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: 56533eb9ac21ba0edf2244b7
title: Concatenating Strings with Plus Operator
title: 用加号运算符连接字符串
challengeType: 1
videoUrl: 'https://scrimba.com/c/cNpM8AN'
forumTopicId: 16802
@ -9,49 +9,48 @@ dashedName: concatenating-strings-with-plus-operator
# --description--
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.
JavaScript 中,当 `+` 操作符被用于一个 `String` 类型的值的时候,它被称作<dfn>拼接</dfn>操作符。 你可以通过<dfn>拼接</dfn>其他字符串来创建一个新的字符串。
**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."
```
字符串 `I come first. I come second.` 将显示在控制台中。
# --instructions--
Build `myStr` from the strings `"This is the start. "` and `"This is the end."` using the `+` operator.
使用 `+` 操作符连接字符串`This is the start.` `This is the end.` 赋值给 `myStr`
# --hints--
`myStr` should have a value of `This is the start. This is the end.`
`myStr` 的值应该是 `This is the start. This is the end.`
```js
assert(myStr === 'This is the start. This is the end.');
```
You should use the `+` operator to build `myStr`.
应使用 `+` 操作符创建 `myStr`
```js
assert(code.match(/(["']).*\1\s*\+\s*(["']).*\2/g));
```
`myStr` should be created using the `var` keyword.
应使用 `var` 关键字创建 `myStr`
```js
assert(/var\s+myStr/.test(code));
```
You should assign the result to the `myStr` variable.
应把结果赋值给 `myStr` 变量。
```js
assert(/myStr\s*=/.test(code));

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244b8
title: Concatenating Strings with the Plus Equals Operator
title: 用 += 运算符连接字符串
challengeType: 1
videoUrl: 'https://scrimba.com/c/cbQmmC4'
forumTopicId: 16803
@ -9,32 +9,32 @@ dashedName: concatenating-strings-with-the-plus-equals-operator
# --description--
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.
我们还可以使用 `+=` 运算符来<dfn>拼接</dfn>字符串到现有字符串变量的结尾。 对于那些被分割成几段的长的字符串来说,这一操作是非常有用的。
**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."
```
`ourStr` 现在内容为字符串 `I come first. I come second.`
# --instructions--
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.
使用 `+=` 操作符,多行合并字符串 `This is the first sentence.` `This is the second sentence.` ,并赋值给 `myStr` 。 像编辑器里显示的那样使用 `+=` 操作符。 先把第一个字符串赋值给 `myStr`,然后拼接第二个字符串。
# --hints--
`myStr` should have a value of `This is the first sentence. This is the second sentence.`
`myStr` 的值应该是 `This is the first sentence. This is the second sentence.`
```js
assert(myStr === 'This is the first sentence. This is the second sentence.');
```
You should use the `+=` operator to build `myStr`.
应该使用 `+=` 操作符创建 `myStr` 变量。
```js
assert(code.match(/myStr\s*\+=\s*(["']).*\1/g));

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244b9
title: Constructing Strings with Variables
title: 用变量构造字符串
challengeType: 1
videoUrl: 'https://scrimba.com/c/cqk8rf4'
forumTopicId: 16805
@ -9,29 +9,30 @@ dashedName: constructing-strings-with-variables
# --description--
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.
有时候你需要创建一个类似 [Mad Libs](https://en.wikipedia.org/wiki/Mad_Libs)(填词游戏)风格的字符串。 通过使用连接运算符(`+`),你可以插入一个或多个变量来组成一个字符串。
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?"
```
`ourStr` 值为 `Hello, our name is freeCodeCamp, how are you?`
# --instructions--
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!"`
把你的名字赋值给变量 `myName`,然后把变量 `myName` 插入到字符串 `My name is` `and I am well!` 之间,并把连接后的结果赋值给变量 `myStr`
# --hints--
`myName` should be set to a string at least 3 characters long.
`myName` 应该是一个至少有 3 个字符的字符串。
```js
assert(typeof myName !== 'undefined' && myName.length > 2);
```
You should use two `+` operators to build `myStr` with `myName` inside it.
使用两个 `+` 操作符创建包含 `myName``myStr` 变量。
```js
assert(code.match(/["']\s*\+\s*myName\s*\+\s*["']/g).length > 0);

View File

@ -1,6 +1,6 @@
---
id: 56105e7b514f539506016a5e
title: Count Backwards With a For Loop
title: 使用 For 循环反向遍历数组
challengeType: 1
videoUrl: 'https://scrimba.com/c/c2R6BHa'
forumTopicId: 16808
@ -9,11 +9,11 @@ dashedName: count-backwards-with-a-for-loop
# --description--
A for loop can also count backwards, so long as we can define the right conditions.
只要我们定义好合适的条件for 循环也可以反向遍历。
In order to decrement by two each iteration, we'll need to change our `initialization`, `condition`, and `final-expression`.
为了让每次递减 2我们需要改变 initializationconditionfinal-expression
We'll start at `i = 10` and loop while `i > 0`. We'll decrement `i` by 2 each loop with `i -= 2`.
设置 `i = 10`,并且当 `i > 0` 的时候才继续循环。 我们使用 `i -= 2` 来让 `i` 每次循环递减 2。
```js
var ourArray = [];
@ -22,27 +22,27 @@ for (var i = 10; i > 0; i -= 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.
循环结束后,`ourArray` 的值为 `[10,8,6,4,2]`。 让我们改变 initializationfinal-expression,这样我们就可以按照奇数从后往前两两倒着数。
# --instructions--
Push the odd numbers from 9 through 1 to `myArray` using a `for` loop.
使用一个 `for`循环,把从 9 到 1 的奇数添加到 `myArray`
# --hints--
You should be using a `for` loop for this.
应该使用 `for` 循环。
```js
assert(/for\s*\([^)]+?\)/.test(code));
```
You should be using the array method `push`.
应该使用数组方法 `push`
```js
assert(code.match(/myArray.push/));
```
`myArray` should equal `[9,7,5,3,1]`.
`myArray` 应该等于 `[9,7,5,3,1]`
```js
assert.deepEqual(myArray, [9, 7, 5, 3, 1]);

View File

@ -1,6 +1,6 @@
---
id: 565bbe00e9cc8ac0725390f4
title: Counting Cards
title: 21 点游戏
challengeType: 1
videoUrl: 'https://scrimba.com/c/c6KE7ty'
forumTopicId: 16809
@ -9,25 +9,25 @@ dashedName: counting-cards
# --description--
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).
在赌场 21 点游戏中,玩家可以通过计算牌桌上已经发放的卡牌的高低值来让自己在游戏中保持优势。 这就叫 [21 点算法](https://en.wikipedia.org/wiki/Card_counting)
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.
牌桌上的大值的卡牌更多,对玩家有利。 根据下面的表格,每张卡牌都被分配了一个值。 如果卡牌的值大于 0那么玩家应该追加赌注。 如果卡牌的值为 0 或负数,玩家应该追加少许赌注甚至不追加赌注。
<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>
<table class='table table-striped'><thead><tr><th>计数</th><th>卡牌</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>
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.
请写一个函数实现 21 点算法。 它根据参数 `card` 的值(见表格,可能是数字或者字符串)来递增或递减全局变量 `count`。 然后函数返回一个由当前 count计数`Bet`(当 count > 0 时)或 `Hold`(当 count <= 0 时) 拼接的字符串。 注意 count计数和玩家的决定`Bet` `Hold`)之间应该有空格。
**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.
**提示:**
当卡牌为 7、8、9 时,不要把 `count` 值重置为 0。 不要返回一个数组。
输出结果中不要包含单引号或双引号。
# --hints--
Cards Sequence 2, 3, 4, 5, 6 should return `5 Bet`
卡牌序列 2、3、4、5、6 应该返回 `5 Bet`
```js
assert(
@ -46,7 +46,7 @@ assert(
);
```
Cards Sequence 7, 8, 9 should return `0 Hold`
卡牌序列 7、8、9 应该返回 `0 Hold`
```js
assert(
@ -63,7 +63,7 @@ assert(
);
```
Cards Sequence 10, J, Q, K, A should return `-5 Hold`
卡牌序列 10、J、Q、K、A 应该返回 `-5 Hold`
```js
assert(
@ -82,7 +82,7 @@ assert(
);
```
Cards Sequence 3, 7, Q, 8, A should return `-1 Hold`
卡牌序列 3、7、Q、8、A 应该返回 `-1 Hold`
```js
assert(
@ -101,7 +101,7 @@ assert(
);
```
Cards Sequence 2, J, 9, 2, 7 should return `1 Bet`
卡牌序列 2、J、9、2、7 应该返回 `1 Bet`
```js
assert(
@ -120,7 +120,7 @@ assert(
);
```
Cards Sequence 2, 2, 10 should return `1 Bet`
卡牌序列 2、2、10 应该返回 `1 Bet`
```js
assert(
@ -137,7 +137,7 @@ assert(
);
```
Cards Sequence 3, 2, A, 10, K should return `-1 Hold`
卡牌序列 3、2、A、10、K 应该返回 `-1 Hold`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: cf1391c1c11feddfaeb4bdef
title: Create Decimal Numbers with JavaScript
title: 创建一个小数
challengeType: 1
videoUrl: 'https://scrimba.com/c/ca8GEuW'
forumTopicId: 16826
@ -9,24 +9,23 @@ dashedName: create-decimal-numbers-with-javascript
# --description--
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>或者 <dfn>floats</dfn>
**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).
**提示:**不是所有的实数都可以用浮点数(<dfn>floating point</dfn>)来表示。 因为可能产生四舍五入的错误, [查看详情](https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems)。
# --instructions--
Create a variable `myDecimal` and give it a decimal value with a fractional part (e.g. `5.7`).
创建一个变量 `myDecimal`,并给它赋值一个浮点数(例如 `5.7`)
# --hints--
`myDecimal` should be a number.
`myDecimal` 应该是一个数字。
```js
assert(typeof myDecimal === 'number');
```
`myDecimal` should have a decimal point
`myDecimal` 应该包含小数点。
```js
assert(myDecimal % 1 != 0);

View File

@ -1,6 +1,6 @@
---
id: bd7123c9c444eddfaeb5bdef
title: Declare String Variables
title: 声明字符串变量
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"` 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.
`"your name"` 被称作<dfn>字符串</dfn><dfn>变量</dfn>。 字符串是用单引号或双引号包裹起来的一连串的零个或多个字符。
# --instructions--
Create two new `string` variables: `myFirstName` and `myLastName` and assign them the values of your first and last name, respectively.
创建两个新的 string 变量:`myFirstName` `myLastName`,并用你的姓和名分别为它们赋值。
# --hints--
`myFirstName` should be a string with at least one character in it.
`myFirstName` 应该是一个字符串,并且至少包含一个字符。
```js
assert(
@ -39,7 +39,7 @@ assert(
);
```
`myLastName` should be a string with at least one character in it.
`myLastName` 应该是一个字符串,并且至少包含一个字符。
```js
assert(
@ -66,7 +66,9 @@ if(typeof myFirstName !== "undefined" && typeof myLastName !== "undefined"){(fun
```
## --seed-contents--
```js
```
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244ad
title: Decrement a Number with JavaScript
title: 数字递减
challengeType: 1
videoUrl: 'https://scrimba.com/c/cM2KeS2'
forumTopicId: 17558
@ -9,30 +9,29 @@ dashedName: decrement-a-number-with-javascript
# --description--
You can easily <dfn>decrement</dfn> or decrease a variable by one with the `--` operator.
使用自减符号`--`,你可以很方便地对一个变量执行<dfn>自减</dfn>或者 -1 运算。
`i--;`
is the equivalent of
等效于
`i = i - 1;`
**Note**
The entire line becomes `i--;`, eliminating the need for the equal sign.
**提示** `i--;` 这种写法,省去了书写等号的必要。
# --instructions--
Change the code to use the `--` operator on `myVar`.
重写代码,使用 `--` 符号对 `myVar` 执行自减操作。
# --hints--
`myVar` should equal `10`.
`myVar` 应该等于`10`
```js
assert(myVar === 10);
```
`myVar = myVar - 1;` should be changed.
`myVar = myVar - 1;` 语句应该被修改。
```js
assert(
@ -40,13 +39,13 @@ assert(
);
```
You should use the `--` operator on `myVar`.
`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: Delete Properties from a JavaScript Object
title: 删除对象的属性
challengeType: 1
videoUrl: 'https://scrimba.com/c/cDqKdTv'
forumTopicId: 17560
@ -9,11 +9,11 @@ dashedName: delete-properties-from-a-javascript-object
# --description--
We can also delete properties from objects like this:
我们同样可以删除对象的属性,例如:
`delete ourDog.bark;`
Example:
例如:
```js
var ourDog = {
@ -27,7 +27,7 @@ var ourDog = {
delete ourDog.bark;
```
After the last line shown above, `ourDog` looks like:
在上面代码的最后一行中,`ourDog` 是这样的:
```js
{
@ -40,17 +40,17 @@ After the last line shown above, `ourDog` looks like:
# --instructions--
Delete the `"tails"` property from `myDog`. You may use either dot or bracket notation.
删除 `myDog` 对象的 `tails` 属性。 可以使用点操作符或者中括号操作符。
# --hints--
You should delete the property `"tails"` from `myDog`.
应该从 `myDog` 中删除 `tails` 属性。
```js
assert(typeof myDog === 'object' && myDog.tails === undefined);
```
You should not modify the `myDog` setup.
不要修改 `myDog` 的初始化代码。
```js
assert(code.match(/"tails": 1/g).length > 0);

View File

@ -1,6 +1,6 @@
---
id: cf1111c1c11feddfaeb6bdef
title: Divide One Number by Another with JavaScript
title: 除法运算
challengeType: 1
videoUrl: 'https://scrimba.com/c/cqkbdAr'
forumTopicId: 17566
@ -9,29 +9,30 @@ dashedName: divide-one-number-by-another-with-javascript
# --description--
We can also divide one number by another.
我们可以在 JavaScript 中做除法运算。
JavaScript uses the `/` symbol for division.
JavaScript 中使用 `/` 符号做除法运算。
**Example**
**示例**
```js
myVar = 16 / 2; // assigned 8
myVar = 16 / 2;
```
现在,变量 `myVar` 的值为 `8`
# --instructions--
Change the `0` so that the `quotient` is equal to `2`.
改变数值 `0` 来让变量 `quotient` 的值等于 `2`
# --hints--
The variable `quotient` should be equal to 2.
要使 `quotient` 的值等于 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: Escape Sequences in Strings
title: 转义字符
challengeType: 1
videoUrl: 'https://scrimba.com/c/cvmqRh6'
forumTopicId: 17567
@ -9,36 +9,36 @@ dashedName: escape-sequences-in-strings
# --description--
Quotes are not the only characters that can be <dfn>escaped</dfn> inside a string. There are two reasons to use escaping characters:
引号不是字符串中唯一可以被 <dfn>转义</dfn> 的字符。 使用转义字符有两个原因:
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.
1. 首先是可以让你使用无法输入的字符,例如退格。
2. 其次是可以让你在一个字符串中表示多个引号,而不会出错。
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>
<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>
*Note that the backslash itself must be escaped in order to display as a backslash.*
*请注意,必须对反斜杠本身进行转义,它才能显示为反斜杠。*
# --instructions--
Assign the following three lines of text into the single variable `myStr` using escape sequences.
使用转义序列把下面三行文本赋值给一个变量 `myStr`
<blockquote>FirstLine<br>    \SecondLine<br>ThirdLine</blockquote>
<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.
你需要使用转义字符正确地插入特殊字符, 确保间距与上面文本一致,并且单词或转义字符之间没有空格。
**Note:** The indentation for `SecondLine` is achieved with the tab escape character, not spaces.
**注意:** `SecondLine` 是因为键入了转义字符(而不是空格),所以在那个位置。
# --hints--
`myStr` should not contain any spaces
`myStr` 不能包含空格。
```js
assert(!/ /.test(myStr));
```
`myStr` should contain the strings `FirstLine`, `SecondLine` and `ThirdLine` (remember case sensitivity)
`myStr` 应包含字符串 `FirstLine``SecondLine` `ThirdLine`(记得区分大小写)。
```js
assert(
@ -46,31 +46,31 @@ assert(
);
```
`FirstLine` should be followed by the newline character `\n`
`FirstLine` 后面应该是一个换行符 `\n`
```js
assert(/FirstLine\n/.test(myStr));
```
`myStr` should contain a tab character `\t` which follows a newline character
`myStr` 应该包含一个制表符 `\t`,它在换行符后面。
```js
assert(/\n\t/.test(myStr));
```
`SecondLine` should be preceded by the backslash character <code>\\</code>
`SecondLine` 前面应该是反斜杠 `\`
```js
assert(/\\SecondLine/.test(myStr));
```
There should be a newline character between `SecondLine` and `ThirdLine`
`SecondLine` `ThirdLine` 之间应该是换行符。
```js
assert(/SecondLine\nThirdLine/.test(myStr));
```
`myStr` should only contain characters shown in the instructions
`myStr` 应该只包含上面要求的字符。
```js
assert(myStr === 'FirstLine\n\t\\SecondLine\nThirdLine');

View File

@ -11,7 +11,7 @@ dashedName: escaping-literal-quotes-in-strings
定义一个字符串必须要用单引号或双引号来包裹它。 那么当你的字符串里面包含引号 `"` 或者 `'` 时该怎么办呢?
在 JavaScript 中,可以通过在引号前面使用<dfn>反斜杠</dfn><code>\\</code>)来<dfn>转义</dfn>引号。
在 JavaScript 中,可以通过在引号前面使用<dfn>反斜杠</dfn>`\`)来<dfn>转义</dfn>引号。
`var sampleStr = "Alan said, \"Peter is learning JavaScript\".";`

View File

@ -1,6 +1,6 @@
---
id: bd7123c9c448eddfaeb5bdef
title: Find the Length of a String
title: 查找字符串的长度
challengeType: 1
videoUrl: 'https://scrimba.com/c/cvmqEAd'
forumTopicId: 18182
@ -9,19 +9,23 @@ dashedName: find-the-length-of-a-string
# --description--
You can find the length of a `String` value by writing `.length` after the string variable or string literal.
你可以通过在字符串变量或字符串后面写上 `.length` 来获得 `String` 的长度。
`"Alan Peter".length; // 10`
```js
console.log("Alan Peter".length);
```
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.
字符串 `10` 将会出现在控制台中。
例如,我们创建了一个变量 `var firstName = "Charles"`,我们就可以通过使用 `firstName.length` 来获得 `Charles` 字符串的长度。
# --instructions--
Use the `.length` property to count the number of characters in the `lastName` variable and assign it to `lastNameLength`.
使用 `.length` 属性来获得变量 `lastName` 的长度,并把它赋值给变量 `lastNameLength`
# --hints--
You should not change the variable declarations in the `// Setup` section.
不能改变 `// Setup` 部分声明的变量。
```js
assert(
@ -30,13 +34,13 @@ assert(
);
```
`lastNameLength` should be equal to eight.
`lastNameLength` 应该等于 8。
```js
assert(typeof lastNameLength !== 'undefined' && lastNameLength === 8);
```
You should be getting the length of `lastName` by using `.length` like this: `lastName.length`.
你应该使用 `.length` 获取 `lastName` 的长度,像这样 `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: Finding a Remainder in JavaScript
title: 求余运算
challengeType: 1
videoUrl: 'https://scrimba.com/c/cWP24Ub'
forumTopicId: 18184
@ -9,39 +9,38 @@ dashedName: finding-a-remainder-in-javascript
# --description--
The <dfn>remainder</dfn> operator `%` gives the remainder of the division of two numbers.
<dfn>remainder</dfn> 求余运算符 `%` 返回两个数相除得到的余数
**Example**
**示例**
<blockquote>5 % 2 = 1 because<br>Math.floor(5 / 2) = 2 (Quotient)<br>2 * 2 = 4<br>5 - 4 = 1 (Remainder)</blockquote>
<blockquote>5 % 2 = 1 因为<br>Math.floor(5 / 2) = 2 (商)<br>2 * 2 = 4<br>5 - 4 = 1 (余数)</blockquote>
**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`.
**用法**
在数学中,判断一个数是奇数还是偶数,只需要判断这个数除以 `2` 得到的余数是 0 还是 1。
<blockquote>17 % 2 = 1 (17 is Odd)<br>48 % 2 = 0 (48 is Even)</blockquote>
<blockquote>17 % 2 = 117 是奇数)<br>48 % 2 = 048 是偶数)</blockquote>
**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.
**提示**余数运算符(<dfn>remainder</dfn>)有时被错误地称为“模数”运算符。 它与模数非常相似,但不能用于负数的运算。
# --instructions--
Set `remainder` equal to the remainder of `11` divided by `3` using the <dfn>remainder</dfn> (`%`) operator.
使用 <dfn>remainder</dfn> `%`)运算符,计算 `11` 除以 `3` 的余数,并把余数赋给变量 `remainder`
# --hints--
The variable `remainder` should be initialized
变量 `remainder` 应该被初始化。
```js
assert(/var\s+?remainder/.test(code));
```
The value of `remainder` should be `2`
`remainder` 的值应该等于 `2`
```js
assert(remainder === 2);
```
You should use the `%` operator
你应该使用 `%` 运算符。
```js
assert(/\s+?remainder\s*?=\s*?.*%.*;?/.test(code));

View File

@ -1,6 +1,6 @@
---
id: cf1111c1c11feddfaeb9bdef
title: Generate Random Fractions with JavaScript
title: 使用 JavaScript 生成随机分数
challengeType: 1
videoUrl: 'https://scrimba.com/c/cyWJJs3'
forumTopicId: 18185
@ -9,32 +9,31 @@ dashedName: generate-random-fractions-with-javascript
# --description--
Random numbers are useful for creating random behavior.
随机数非常适合用来创建随机行为。
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`
JavaScript 中,可以用 `Math.random()` 生成一个在`0`(包括 0`1`(不包括 1之间的随机小数 因此 `Math.random()` 可能返回 `0`,但绝不会返回 `1`
**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.
**提示:** [使用赋值运算符存储值](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator)这一节讲过,所有函数调用将在 `return` 执行之前结束,因此我们可以 `return`(返回)`Math.random()` 函数的值。
# --instructions--
Change `randomFraction` to return a random number instead of returning `0`.
更改 `randomFraction`,使其返回一个随机数而不是 `0`
# --hints--
`randomFraction` should return a random number.
`randomFraction` 应该返回一个随机数。
```js
assert(typeof randomFraction() === 'number');
```
The number returned by `randomFraction` should be a decimal.
`randomFraction` 应该返回一个小数。
```js
assert((randomFraction() + '').match(/\./g));
```
You should be using `Math.random` to generate the random decimal number.
需要使用 `Math.random` 生成随机的小数。
```js
assert(code.match(/Math\.random/g).length >= 0);

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244c0
title: Global vs. Local Scope in Functions
title: 函数中的全局作用域和局部作用域
challengeType: 1
videoUrl: 'https://scrimba.com/c/c2QwKH2'
forumTopicId: 18194
@ -9,9 +9,9 @@ dashedName: global-vs--local-scope-in-functions
# --description--
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.
一个程序中有可能具有相同名称的<dfn>局部</dfn>变量 和<dfn>全局</dfn>变量。 在这种情况下,`local` 变量将会优先于`global`变量。
In this example:
下面为例:
```js
var someVar = "Hat";
@ -21,27 +21,27 @@ function myFun() {
}
```
The function `myFun` will return `"Head"` because the `local` version of the variable is present.
函数 `myFun` 将会返回 `Head`,因为 `local` 变量优先级更高。
# --instructions--
Add a local variable to `myOutfit` function to override the value of `outerWear` with `"sweater"`.
`myOutfit` 添加一个局部变量来将 `outerWear` 的值重载为 `sweater`
# --hints--
You should not change the value of the global `outerWear`.
不要修改全局变量 `outerWear` 的值。
```js
assert(outerWear === 'T-Shirt');
```
`myOutfit` should return `"sweater"`.
`myOutfit` 应该返回 `sweater`
```js
assert(myOutfit() === 'sweater');
```
You should not change the return statement.
不要修改 return 语句。
```js
assert(/return outerWear/.test(code));

View File

@ -1,6 +1,6 @@
---
id: 5664820f61c48e80c9fa476c
title: Golf Code
title: 高尔夫代码
challengeType: 1
videoUrl: 'https://scrimba.com/c/c9ykNUR'
forumTopicId: 18195
@ -9,77 +9,77 @@ dashedName: golf-code
# --description--
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.
在[高尔夫](https://en.wikipedia.org/wiki/Golf)游戏中,每个洞都有自己的标准杆数 `par`,代表着把球打进洞所挥杆的平均次数 `strokes`。 根据你把球打进洞所挥杆的次数 `strokes` 高于或低于 `par` 多少,有一个不同的昵称(代表打高尔夫球的水平)。
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):
函数将会传送两个参数,`par` `strokes`。 根据下表返回正确的字符串。下表列出不同挥杆次数(从高到低)对应的字符串。
<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>
<table class='table table-striped'><thead><tr><th>挥杆次数</th><th>返回字符串</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` and `strokes` will always be numeric and positive. We have added an array of all the names for your convenience.
`par` `strokes` 必须是数字而且是正数。 题目已定义字符串的数组,便于你操作。
# --hints--
`golfScore(4, 1)` should return "Hole-in-one!"
`golfScore(4, 1)` 应该返回字符串 `Hole-in-one!`
```js
assert(golfScore(4, 1) === 'Hole-in-one!');
```
`golfScore(4, 2)` should return "Eagle"
`golfScore(4, 2)` 应该返回字符串 `Eagle`
```js
assert(golfScore(4, 2) === 'Eagle');
```
`golfScore(5, 2)` should return "Eagle"
`golfScore(5, 2)` 应该返回字符串 `Eagle`
```js
assert(golfScore(5, 2) === 'Eagle');
```
`golfScore(4, 3)` should return "Birdie"
`golfScore(4, 3)` 应该返回字符串 `Birdie`
```js
assert(golfScore(4, 3) === 'Birdie');
```
`golfScore(4, 4)` should return "Par"
`golfScore(4, 4)` 应该返回字符串 `Par`
```js
assert(golfScore(4, 4) === 'Par');
```
`golfScore(1, 1)` should return "Hole-in-one!"
`golfScore(1, 1)` 应该返回字符串 `Hole-in-one!`
```js
assert(golfScore(1, 1) === 'Hole-in-one!');
```
`golfScore(5, 5)` should return "Par"
`golfScore(5, 5)` 应该返回字符串 `Par`
```js
assert(golfScore(5, 5) === 'Par');
```
`golfScore(4, 5)` should return "Bogey"
`golfScore(4, 5)` 应该返回字符串 `Bogey`
```js
assert(golfScore(4, 5) === 'Bogey');
```
`golfScore(4, 6)` should return "Double Bogey"
`golfScore(4, 6)` 应该返回字符串 `Double Bogey`
```js
assert(golfScore(4, 6) === 'Double Bogey');
```
`golfScore(4, 7)` should return "Go Home!"
`golfScore(4, 7)` 应该返回字符串 `Go Home!`
```js
assert(golfScore(4, 7) === 'Go Home!');
```
`golfScore(5, 9)` should return "Go Home!"
`golfScore(5, 9)` 应该返回字符串 `Go Home!`
```js
assert(golfScore(5, 9) === 'Go Home!');

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244ac
title: Increment a Number with JavaScript
title: 数字递增
challengeType: 1
videoUrl: 'https://scrimba.com/c/ca8GLT9'
forumTopicId: 18201
@ -9,20 +9,19 @@ dashedName: increment-a-number-with-javascript
# --description--
You can easily <dfn>increment</dfn> or add one to a variable with the `++` operator.
使用 `++`,我们可以很容易地对变量进行<dfn>自增</dfn>或者 +1 运算。
`i++;`
is the equivalent of
等效于
`i = i + 1;`
**Note**
The entire line becomes `i++;`, eliminating the need for the equal sign.
**提示** `i++;` 这种写法,省去了书写等号的必要。
# --instructions--
Change the code to use the `++` operator on `myVar`.
重写代码,使用 `++` 来对变量 `myVar` 进行自增操作。
# --hints--
@ -32,7 +31,7 @@ Change the code to use the `++` operator on `myVar`.
assert(myVar === 88);
```
You should not use the assignment operator.
不应该使用赋值运算符。
```js
assert(
@ -40,13 +39,13 @@ assert(
);
```
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: 56533eb9ac21ba0edf2244db
title: Introducing Else If Statements
title: 介绍 else if 语句
challengeType: 1
videoUrl: 'https://scrimba.com/c/caeJ2hm'
forumTopicId: 18206
@ -9,7 +9,7 @@ dashedName: introducing-else-if-statements
# --description--
If you have multiple conditions that need to be addressed, you can chain `if` statements together with `else if` statements.
如果你有多个条件语句,你可以通过 `else if` 语句把 `if` 语句链起来。
```js
if (num > 15) {
@ -23,23 +23,23 @@ if (num > 15) {
# --instructions--
Convert the logic to use `else if` statements.
使用 `else if` 实现同样的效果。
# --hints--
You should have at least two `else` statements
你应该至少有两个 `else` 表达式。
```js
assert(code.match(/else/g).length > 1);
```
You should have at least two `if` statements
你应该至少有两个 `if` 表达式。
```js
assert(code.match(/if/g).length > 1);
```
You should have closing and opening curly braces for each `if else` code block.
应该关闭每一个 `if else` 代码块。
```js
assert(
@ -49,31 +49,31 @@ assert(
);
```
`testElseIf(0)` should return "Smaller than 5"
`testElseIf(0)` 应该返回字符串 `Smaller than 5`
```js
assert(testElseIf(0) === 'Smaller than 5');
```
`testElseIf(5)` should return "Between 5 and 10"
`testElseIf(5)` 应该返回字符串 `Between 5 and 10`
```js
assert(testElseIf(5) === 'Between 5 and 10');
```
`testElseIf(7)` should return "Between 5 and 10"
`testElseIf(7)` 应该返回字符串 `Between 5 and 10`
```js
assert(testElseIf(7) === 'Between 5 and 10');
```
`testElseIf(10)` should return "Between 5 and 10"
`testElseIf(10)` 应该返回字符串 `Between 5 and 10`
```js
assert(testElseIf(10) === 'Between 5 and 10');
```
`testElseIf(12)` should return "Greater than 10"
`testElseIf(12)` 应该返回字符串 `Greater than 10`
```js
assert(testElseIf(12) === 'Greater than 10');

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244da
title: Introducing Else Statements
title: 介绍 else 语句
challengeType: 1
videoUrl: 'https://scrimba.com/c/cek4Efq'
forumTopicId: 18207
@ -9,7 +9,7 @@ dashedName: introducing-else-statements
# --description--
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.
`if` 语句的条件为真,会执行大括号里的代码。 那如果条件为假呢? 正常情况下什么也不会发生。 使用 `else` 语句,可以执行当条件为假时相应的代码。
```js
if (num > 10) {
@ -21,47 +21,47 @@ if (num > 10) {
# --instructions--
Combine the `if` statements into a single `if/else` statement.
请把多个 `if` 语句合并为一个 `if/else` 语句。
# --hints--
You should only have one `if` statement in the editor
应该只有一个 `if` 语句。
```js
assert(code.match(/if/g).length === 1);
```
You should use an `else` statement
应该使用一个 `else` 语句。
```js
assert(/else/g.test(code));
```
`testElse(4)` should return "5 or Smaller"
`testElse(4)` 应该返回字符串 `5 or Smaller`
```js
assert(testElse(4) === '5 or Smaller');
```
`testElse(5)` should return "5 or Smaller"
`testElse(5)` 应该返回字符串 `5 or Smaller`
```js
assert(testElse(5) === '5 or Smaller');
```
`testElse(6)` should return "Bigger than 5"
`testElse(6)` 应该返回字符串 `Bigger than 5`
```js
assert(testElse(6) === 'Bigger than 5');
```
`testElse(10)` should return "Bigger than 5".
`testElse(10)` 应该返回字符串 `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: Iterate Odd Numbers With a For Loop
title: 使用 For 循环遍历数组的奇数
challengeType: 1
videoUrl: 'https://scrimba.com/c/cm8n7T9'
forumTopicId: 18212
@ -9,9 +9,9 @@ dashedName: iterate-odd-numbers-with-a-for-loop
# --description--
For loops don't have to iterate one at a time. By changing our `final-expression`, we can count by even numbers.
对于循环,一次不必递增一个。 通过更改我们的 `final-expression`,我们可以用偶数来计数。
We'll start at `i = 0` and loop while `i < 10`. We'll increment `i` by 2 each loop with `i += 2`.
初始化 `i = 0`,当 `i < 10` 的时候继续循环。 `i += 2``i` 每次循环之后增加 2。
```js
var ourArray = [];
@ -20,21 +20,21 @@ for (var i = 0; i < 10; i += 2) {
}
```
`ourArray` will now contain `[0,2,4,6,8]`. Let's change our `initialization` so we can count by odd numbers.
循环结束后,`ourArray` 的值为 `[0,2,4,6,8]`。 改变计数器(`initialization` ,这样我们可以用奇数来递增。
# --instructions--
Push the odd numbers from 1 through 9 to `myArray` using a `for` loop.
写一个 `for` 循环,把从 1 到 9 的奇数添加到 `myArray`
# --hints--
You should be using a `for` loop for this.
应该使用 `for` 循环。
```js
assert(/for\s*\([^)]+?\)/.test(code));
```
`myArray` should equal `[1,3,5,7,9]`.
`myArray` 应该等于 `[1,3,5,7,9]`
```js
assert.deepEqual(myArray, [1, 3, 5, 7, 9]);

View File

@ -1,6 +1,6 @@
---
id: 5675e877dbd60be8ad28edc6
title: Iterate Through an Array with a For Loop
title: 使用 For 循环遍历数组
challengeType: 1
videoUrl: 'https://scrimba.com/c/caeR3HB'
forumTopicId: 18216
@ -9,7 +9,7 @@ dashedName: iterate-through-an-array-with-a-for-loop
# --description--
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:
JavaScript 中的一个常见任务是遍历数组的内容。 一种方法是使用 `for` 循环。 下面的代码将输出数组 `arr` 的每个元素到控制台:
```js
var arr = [10, 9, 8, 7, 6];
@ -18,33 +18,33 @@ for (var i = 0; i < arr.length; i++) {
}
```
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.
记住数组的索引从零开始的,这意味着数组的最后一个元素的下标是:`length - 1`(数组的长度 -1。 我们这个循环的条件是 `i < arr.length`,当 `i` 的值为 `length` 的时候循环就停止了。 在这个例子中,最后一个循环是 `i === 4`,也就是说,当 `i` 的值等于 `arr.length` 时,结果输出 `6`
# --instructions--
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`.
声明并初始化一个变量 `total` 值为 `0`。 使用 `for` 循环,使得 `total` 的值为 `myArr` 的数组中的每个元素的值的总和。
# --hints--
`total` should be declared and initialized to 0.
`total` 应该被声明, 并且初始化值为 0
```js
assert(code.match(/(var|let|const)\s*?total\s*=\s*0.*?;?/));
```
`total` should equal 20.
`total` 应该等于 20
```js
assert(total === 20);
```
You should use a `for` loop to iterate through `myArr`.
你应该使用 `for` 循环在 `myArr` 中遍历。
```js
assert(/for\s*\(/g.test(code) && /myArr\s*\[/g.test(code));
```
You should not attempt to directly assign the value 20 to `total`.
不能直接把 `total` 设置成 20。
```js
assert(!__helpers.removeWhiteSpace(code).match(/total[=+-]0*[1-9]+/gm));

View File

@ -1,6 +1,6 @@
---
id: 5a2efd662fb457916e1fe604
title: Iterate with JavaScript Do...While Loops
title: do...while 循环
challengeType: 1
videoUrl: 'https://scrimba.com/c/cDqWGcp'
forumTopicId: 301172
@ -9,7 +9,7 @@ dashedName: iterate-with-javascript-do---while-loops
# --description--
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`.
下一种循环叫作 `do...while` 循环。 它被称为 `do...while` 循环,是因为不论什么情况,它都会首先 `do`(运行)循环里的第一部分代码,然后 `while`(当)规定的条件被评估为 `true`(真)的时候,它会继续运行循环。
```js
var ourArray = [];
@ -20,7 +20,7 @@ do {
} 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`:
上面的示例行为类似于其他类型的循环,由此产生的数组将看起来像 `[0, 1, 2, 3, 4]`。 然而,`do...while` 不同于其他循环的地方,是第一次循环检查失败时的行为。 让我们看看代码中的区别:这里是一个常规的 `while` 循环,只要 `i < 5`,就会在循环中运行代码:
```js
var ourArray = [];
@ -31,7 +31,7 @@ while (i < 5) {
}
```
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:
这个例子中,定义了一个空数组 `ourArray` 以及一个值为 5 的 `i` 。 当执行 `while` 循环时,因为 `i` 不小于 5所以循环条件为 `false`,循环内的代码将不会执行。 `ourArray` 最终没有添加任何内容因此示例中的所有代码执行完时ourArray 仍然是`[]`。 现在,看一下 `do...while` 循环。
```js
var ourArray = [];
@ -42,27 +42,27 @@ do {
} while (i < 5);
```
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.
在这里,和使用 `while` 循环一样,将 `i` 的值初始化为 5。 执行下一行时,没有执行循环检查,直接执行花括号内的代码。 数组会添加一个元素,并在进行条件检查之前递增 `i`。 然后,在条件检查时因为 `i` 等于 6 不符合条件 `i < 5`,所以退出循环。 最终 `ourArray` 的值是 `[5]`。 本质上,`do...while` 循环确保循环内的代码至少运行一次。 让我们通过 `do...while` 循环将值添加到数组中。
# --instructions--
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.
将代码中的 `while` 循环更改为 `do...while` 循环,将数字 `10` 添加到 `myArray` 中,代码执行完时,`i` 等于 `11`
# --hints--
You should be using a `do...while` loop for this exercise.
你应该使用 `do...while` 循环。
```js
assert(code.match(/do/g));
```
`myArray` should equal `[10]`.
`myArray` 应该等于 `[10]`
```js
assert.deepEqual(myArray, [10]);
```
`i` should equal `11`
`i` 应该等于 `11`
```js
assert.equal(i, 11);

View File

@ -1,6 +1,6 @@
---
id: cf1111c1c11feddfaeb5bdef
title: Iterate with JavaScript For Loops
title: for 循环
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.
你可以使用循环多次执行相同的代码。
The most common type of JavaScript loop is called a `for` loop because it runs "for" a specific number of times.
JavaScript 中最常见的循环就是 `for`,它可以循环指定次数。
For loops are declared with three optional expressions separated by semicolons:
for 循环中的可选三个表达式用分号隔开:
`for ([initialization]; [condition]; [final-expression])`
`for (a; b; c)`,其中 `a` 为初始化语句,`b` 是循环条件语句,`c` 是终止循环条件表达式。
The `initialization` statement is executed one time only before the loop starts. It is typically used to define and setup your loop variable.
初始化语句只会在执行循环开始之前执行一次。 它通常用于定义和设置你的循环变量。
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.
循环条件语句会在每一轮循环的开始前执行,只要条件判断为 `true` 就会继续执行循环。 当条件为 `false` 的时候,循环将停止执行。 这意味着,如果条件在一开始就为 false这个循环将不会执行。
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.
终止循环表达式在每次循环迭代结束, 在下一个条件检查之前时执行,通常用来递增或递减循环计数。
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`.
在下面的例子中,先初始化 `i = 0`,条件 `i < 5` true 时,进入循环。 每次循环后 `i` 的值增加 `1`,然后执行终止循环条件表达式 `i++`
```js
var ourArray = [];
@ -32,21 +32,21 @@ for (var i = 0; i < 5; i++) {
}
```
`ourArray` will now contain `[0,1,2,3,4]`.
最终 `ourArray` 的值为 `[0,1,2,3,4]`.
# --instructions--
Use a `for` loop to work to push the values 1 through 5 onto `myArray`.
使用 `for` 循环把从 1 到 5 添加进 `myArray` 中。
# --hints--
You should be using a `for` loop for this.
你应该使用 `for` 循环。
```js
assert(/for\s*\([^)]+?\)/.test(code));
```
`myArray` should equal `[1,2,3,4,5]`.
`myArray` 应该等于 `[1,2,3,4,5]`
```js
assert.deepEqual(myArray, [1, 2, 3, 4, 5]);

View File

@ -1,6 +1,6 @@
---
id: cf1111c1c11feddfaeb1bdef
title: Iterate with JavaScript While Loops
title: while 循环
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.
你可以使用循环多次执行相同的代码。
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.
我们将学习的第一种类型的循环称为 `while` 循环,当 while 指定的条件为真,循环才会执行,反之不执行。
```js
var ourArray = [];
@ -22,23 +22,23 @@ while(i < 5) {
}
```
In the code example above, the `while` loop will execute 5 times and append the numbers 0 through 4 to `ourArray`.
在上面的代码里,`while` 循环执行 5 次把 0 到 4 的数字添加到 `ourArray` 数组里。
Let's try getting a while loop to work by pushing values to an array.
让我们通过 while 循环将值添加到数组中。
# --instructions--
Add the numbers 5 through 0 (inclusive) in descending order to `myArray` using a `while` loop.
通过一个 `while` 循环,把从 5 到 0包括 5 和 0 的值添加到 `myArray` 中。
# --hints--
You should be using a `while` loop for this.
你应该使用 `while` 循环。
```js
assert(code.match(/while/g));
```
`myArray` should equal `[5,4,3,2,1,0]`.
`myArray` 应该等于 `[5,4,3,2,1,0]`
```js
assert.deepEqual(myArray, [5, 4, 3, 2, 1, 0]);

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244bf
title: Local Scope and Functions
title: 局部作用域和函数
challengeType: 1
videoUrl: 'https://scrimba.com/c/cd62NhM'
forumTopicId: 18227
@ -9,30 +9,30 @@ 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.
在一个函数内声明的变量,以及该函数的参数都具有局部(<dfn>local</dfn>)作用域。 这意味着它们只在该函数内可见。
Here is a function `myTest` with a local variable called `loc`.
这是在函数 `myTest` 内声明局部变量 `loc` 的例子:
```js
function myTest() {
var loc = "foo";
console.log(loc);
}
myTest(); // logs "foo"
console.log(loc); // loc is not defined
myTest();
console.log(loc);
```
`loc` is not defined outside of the function.
`myTest()` 函数调用将在控制台中显示字符串 `foo``console.log(loc)` 行会产生一个错误,因为 `loc` 没有定义在函数之外。
# --instructions--
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.
编辑器有两个 `console.log` 来帮助您了解正在发生的事情。 检查控制台的代码输出以查看它是如何改变的。 在 `myLocalScope` 中声明一个本地变量 `myVar` 并运行测试。
**Note:** The console will still have 'ReferenceError: myVar is not defined', but this will not cause the tests to fail.
**注意:** 控制台仍将显示 `ReferenceError: myVar is not defined`,但这不会导致测试失败。
# --hints--
The code should not contain a global `myVar` variable.
不应该包含全局的 `myVar` 变量。
```js
function declared() {
@ -41,7 +41,7 @@ function declared() {
assert.throws(declared, ReferenceError);
```
You should add a local `myVar` variable.
需要定义局部的 `myVar` 变量。
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5690307fddb111c6084545d7
title: Logical Order in If Else Statements
title: if else 语句中的逻辑顺序
challengeType: 1
videoUrl: 'https://scrimba.com/c/cwNvMUV'
forumTopicId: 18228
@ -9,13 +9,13 @@ dashedName: logical-order-in-if-else-statements
# --description--
Order is important in `if`, `else if` statements.
`if``else if` 语句中的代码顺序是很重要的。
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,32 +43,34 @@ 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"
bar(0) // "Less than two"
foo(0)
bar(0)
```
`foo(0)` 将返回字符串 `Less than one``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)` should return "Less than 5"
`orderMyLogic(4)` 应该返回字符串 `Less than 5`
```js
assert(orderMyLogic(4) === 'Less than 5');
```
`orderMyLogic(6)` should return "Less than 10"
`orderMyLogic(6)` 应该返回字符串 `Less than 10`
```js
assert(orderMyLogic(6) === 'Less than 10');
```
`orderMyLogic(11)` should return "Greater than or equal to 10"
`orderMyLogic(11)`应该返回 `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: Manipulate Arrays With pop()
title: 使用 pop() 操作数组
challengeType: 1
videoUrl: 'https://scrimba.com/c/cRbVZAB'
forumTopicId: 18236
@ -9,26 +9,28 @@ dashedName: manipulate-arrays-with-pop
# --description--
Another way to change the data in an array is with the `.pop()` function.
改变数组中数据的另一种方法是用 `.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.
`.pop()` 函数用来弹出一个数组末尾的值。 我们可以把这个弹出的值赋给一个变量存储起来。 换句话说就是 `.pop()` 函数移除数组末尾的元素并返回这个元素。
Any type of entry can be "popped" off of an array - numbers, strings, even nested arrays.
数组中任何类型的元素(数值,字符串,甚至是数组)都可以被弹出来 。
```js
var threeArr = [1, 4, 6];
var oneDown = threeArr.pop();
console.log(oneDown); // Returns 6
console.log(threeArr); // Returns [1, 4]
console.log(oneDown);
console.log(threeArr);
```
第一个 `console.log` 将显示值 `6`,第二个将显示值 `[1, 4]`
# --instructions--
Use the `.pop()` function to remove the last item from `myArray`, assigning the "popped off" value to `removedFromMyArray`.
使用 `.pop()` 函数移除 `myArray` 中的最后一个元素,并且把弹出的值赋给 `removedFromMyArray`
# --hints--
`myArray` should only contain `[["John", 23]]`.
`myArray` 应该只包含 `[["John", 23]]`
```js
assert(
@ -42,13 +44,13 @@ assert(
);
```
You should use `pop()` on `myArray`.
`myArray` 使用 `pop()` 函数。
```js
assert(/removedFromMyArray\s*=\s*myArray\s*.\s*pop\s*(\s*)/.test(code));
```
`removedFromMyArray` should only contain `["cat", 2]`.
`removedFromMyArray` 应该只包含 `["cat", 2]`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56bbb991ad1ed5201cd392cb
title: Manipulate Arrays With push()
title: 使用 push() 操作数组
challengeType: 1
videoUrl: 'https://scrimba.com/c/cnqmVtJ'
forumTopicId: 18237
@ -9,29 +9,29 @@ dashedName: manipulate-arrays-with-push
# --description--
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.
`.push()` 接受一个或多个参数(<dfn>parameters</dfn>),并把它压入到数组的末尾。
Examples:
示例:
```js
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"]]
```
`arr1` 现在值为 `[1, 2, 3, 4]``arr2` 值为 `["Stimpson", "J", "cat", ["happy", "joy"]]`
# --instructions--
Push `["dog", 3]` onto the end of the `myArray` variable.
`["dog", 3]` 压入到 `myArray` 变量的末尾。
# --hints--
`myArray` should now equal `[["John", 23], ["cat", 2], ["dog", 3]]`.
`myArray` 现在应该等于 `[["John", 23], ["cat", 2], ["dog", 3]]`
```js
assert(

View File

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

View File

@ -1,6 +1,6 @@
---
id: 56bbb991ad1ed5201cd392ce
title: Manipulate Arrays With unshift()
title: 使用 unshift() 操作数组
challengeType: 1
videoUrl: 'https://scrimba.com/c/ckNDESv'
forumTopicId: 18239
@ -9,26 +9,27 @@ dashedName: manipulate-arrays-with-unshift
# --description--
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.
不仅可以 `shift`(移出)数组中的第一个元素,也可以 `unshift`(移入)一个元素到数组的头部。
`.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.
`.unshift()` 函数用起来就像 `.push()` 函数一样,但不是在数组的末尾添加元素,`unshift()` 在数组的头部添加元素。
Example:
示例:
```js
var ourArray = ["Stimpson", "J", "cat"];
ourArray.shift(); // ourArray now equals ["J", "cat"]
ourArray.shift();
ourArray.unshift("Happy");
// ourArray now equals ["Happy", "J", "cat"]
```
`shift``ourArray` 后值为 `["J", "cat"]`。 在 `unshift``ourArray` 后值为 `["Happy", "J", "cat"]`
# --instructions--
Add `["Paul",35]` to the beginning of the `myArray` variable using `unshift()`.
使用 `unshift()` 函数把 `["Paul",35]` 加入到 `myArray` 的头部。
# --hints--
`myArray` should now have \[["Paul", 35], ["dog", 3]].
`myArray` 现在应该等于 `[["Paul", 35], ["dog", 3]]`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244cb
title: Manipulating Complex Objects
title: 操作复杂对象
challengeType: 1
videoUrl: 'https://scrimba.com/c/c9yNMfR'
forumTopicId: 18208
@ -9,9 +9,9 @@ dashedName: manipulating-complex-objects
# --description--
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>.
有时你可能希望将数据存储在一个灵活的数据结构(<dfn>Data Structure</dfn>)中。 JavaScript 对象是一种灵活的数据结构。 它可以储存字符串(<dfn>strings</dfn>)、数字(<dfn>numbers</dfn>)、布尔值(<dfn>booleans</dfn>)、数组(<dfn>arrays</dfn>)、函数(<dfn>functions</dfn>)和对象(<dfn>objects</dfn>)以及这些值的任意组合。
Here's an example of a complex data structure:
这是一个复杂数据结构的示例:
```js
var ourMusic = [
@ -29,7 +29,7 @@ var ourMusic = [
];
```
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.
这是一个包含一个对象的数组。 该对象有关于专辑的各种元数据(<dfn>metadata</dfn>)。 它也有一个嵌套的 `formats` 数组。 可以将专辑添加到顶级数组来增加更多的专辑记录。 对象将数据以一种键 - 值对的形式保存。 在上面的示例中,`"artist": "Daft Punk"` 有一个键位 `artist` 值为 `Daft Punk` 的属性。 [JavaScript Object Notation](http://www.json.org/) 简称 `JSON` 是可以用于存储数据的数据交换格式。
```json
{
@ -45,40 +45,39 @@ This is an array which contains one object inside. The object has various pieces
}
```
**Note**
You will need to place a comma after every object in the array, unless it is the last object in the array.
**提示:**数组中有多个 JSON 对象的时候,对象与对象之间要用逗号隔开。
# --instructions--
Add a new album to the `myMusic` array. Add `artist` and `title` strings, `release_year` number, and a `formats` array of strings.
添加一个新专辑到 `myMusic` 数组。 添加 `artist` `title` 字符串,`release_year` 数字和 `formats` 字符串数组。
# --hints--
`myMusic` should be an array
`myMusic` 应该是一个数组
```js
assert(Array.isArray(myMusic));
```
`myMusic` should have at least two elements
`myMusic` 应该至少包含两个元素
```js
assert(myMusic.length > 1);
```
`myMusic[1]` should be an object
`myMusic[1]` 应该是一个对象
```js
assert(typeof myMusic[1] === 'object');
```
`myMusic[1]` should have at least 4 properties
`myMusic[1]` 至少要包含四个属性
```js
assert(Object.keys(myMusic[1]).length > 3);
```
`myMusic[1]` should contain an `artist` property which is a string
`myMusic[1]` 应该包含一个类型为字符串的 `artist` 的属性
```js
assert(
@ -86,7 +85,7 @@ assert(
);
```
`myMusic[1]` should contain a `title` property which is a string
`myMusic[1]` 应该包含一个类型为字符串的 `title` 属性
```js
assert(
@ -94,7 +93,7 @@ assert(
);
```
`myMusic[1]` should contain a `release_year` property which is a number
`myMusic[1]` 应该包含一个类型为数字的 `release_year` 属性
```js
assert(
@ -103,7 +102,7 @@ assert(
);
```
`myMusic[1]` should contain a `formats` property which is an array
`myMusic[1]` 应该包含一个类型为数组的 `formats` 属性
```js
assert(
@ -111,7 +110,7 @@ assert(
);
```
`formats` should be an array of strings with at least two elements
`formats`应该是一个至少包含两个字符串元素的数组
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: cf1111c1c11feddfaeb8bdef
title: Modify Array Data With Indexes
title: 通过索引修改数组中的数据
challengeType: 1
videoUrl: 'https://scrimba.com/c/czQM4A8'
forumTopicId: 18241
@ -9,25 +9,26 @@ dashedName: modify-array-data-with-indexes
# --description--
Unlike strings, the entries of arrays are <dfn>mutable</dfn> and can be changed freely.
与字符串的数据不可变不同,数组的数据是可变的( <dfn>mutable</dfn>),可以自由地改变。
**Example**
**示例**
```js
var ourArray = [50,40,30];
ourArray[0] = 15; // equals [15,40,30]
ourArray[0] = 15;
```
**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.
`ourArray` 值为 `[15, 40, 30]`
**注意:**数组名与方括号之间不应该有任何空格,比如`array [0]` 。 尽管 JavaScript 能够正确处理这种情况,但是当其他程序员阅读你写的代码时,这可能让他们感到困惑。
# --instructions--
Modify the data stored at index `0` of `myArray` to a value of `45`.
将数组 `myArray`中索引为 `0`上的值修改为 `45`
# --hints--
`myArray` should now be [45,64,99].
`myArray` 应该等于 `[45,64,99]`
```js
assert(
@ -46,7 +47,7 @@ assert(
);
```
You should be using correct index to modify the value in `myArray`.
你应该使用正确的索引修改 `myArray` 的值。
```js
assert(

View File

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

View File

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

View File

@ -1,6 +1,6 @@
---
id: cf1111c1c11feddfaeb7bdef
title: Nest one Array within Another Array
title: 将一个数组嵌套在另一个数组中
challengeType: 1
videoUrl: 'https://scrimba.com/c/crZQZf8'
forumTopicId: 18247
@ -9,21 +9,21 @@ dashedName: nest-one-array-within-another-array
# --description--
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>
这也叫做多维数组(<dfn>multi-dimensional array</dfn>)。
# --instructions--
Create a nested array called `myArray`.
创建一个名为 `myArray` 的嵌套数组。
# --hints--
`myArray` should have at least one array nested within another array.
`myArray` 应该至少有一个数组嵌套在另一个数组中。
```js
assert(Array.isArray(myArray) && myArray.some(Array.isArray));

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244e1
title: Nesting For Loops
title: 循环嵌套
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++) {
}
```
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.
这里一次输出了 `arr` 中的每个子元素。 提示,对于内部循环,我们可以通过 `arr[i]``.length` 来获得子数组的长度,因为 `arr[i]` 本身就是一个数组。
# --instructions--
Modify function `multiplyAll` so that it returns the product of all the numbers in the sub-arrays of `arr`.
修改函数 `multiplyAll`,获得 `arr` 内部数组的每个数字相乘的结果 product。
# --hints--
`multiplyAll([[1],[2],[3]])` should return `6`
`multiplyAll([[1],[2],[3]])` 应该返回 `6`
```js
assert(multiplyAll([[1], [2], [3]]) === 6);
```
`multiplyAll([[1,2],[3,4],[5,6,7]])` should return `5040`
`multiplyAll([[1,2],[3,4],[5,6,7]])` 应该返回 `5040`
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
`multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])` should return `54`
`multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])` 应该返回 `54`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244bd
title: Passing Values to Functions with Arguments
title: 将值传递给带有参数的函数
challengeType: 1
videoUrl: 'https://scrimba.com/c/cy8rahW'
forumTopicId: 18254
@ -9,9 +9,9 @@ dashedName: passing-values-to-functions-with-arguments
# --description--
<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>.
函数的参数 <dfn>parameters</dfn>)在函数中充当调用函数时传入函数的输入占位符(也叫形参)的作用。 函数调用时,参数可以为一个或多个。 调用函数时输入(或传递 <dfn>"passed"</dfn>)的实际值被称为参数(<dfn>arguments</dfn>)。
Here is a function with two parameters, `param1` and `param2`:
这是带有两个参数的函数,`param1` `param2`
```js
function testFun(param1, param2) {
@ -19,21 +19,21 @@ function testFun(param1, param2) {
}
```
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.
然后我们可以调用 `testFun`,就像这样: `testFun("Hello", "World");`。 我们传入了两个字符串参数, `Hello` `World`。 在函数中,`param1` 等于字符串 `Hello``param2` 等于字符串 `World`。 请注意,`testFun` 函数可以多次调用,每次调用时传递的参数会决定参数的实际值。
# --instructions--
<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>
<ol><li>创建一个名为 <code>functionWithArgs</code> 的函数,它可以接收两个参数,计算参数的和,将结果输出到控制台。</li><li>用两个数字作为参数调用函数。</li></ol>
# --hints--
`functionWithArgs` should be a function.
`functionWithArgs` 应该是一个函数。
```js
assert(typeof functionWithArgs === 'function');
```
`functionWithArgs(1,2)` should output `3`.
`functionWithArgs(1,2)` 应该输出 `3`
```js
if (typeof functionWithArgs === 'function') {
@ -44,7 +44,7 @@ if (typeof functionWithArgs === 'function') {
assert(logOutput == 3);
```
`functionWithArgs(7,9)` should output `16`.
`functionWithArgs(7,9)` 应该输出 `16`
```js
if (typeof functionWithArgs === 'function') {
@ -55,7 +55,7 @@ if (typeof functionWithArgs === 'function') {
assert(logOutput == 16);
```
You should call `functionWithArgs` with two numbers after you define it.
在定义 `functionWithArgs` 之后记得传入两个数字调用它。
```js
assert(
@ -105,7 +105,9 @@ if (typeof functionWithArgs !== "function") {
```
## --seed-contents--
```js
```
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: 599a789b454f2bbd91a3ff4d
title: Practice comparing different values
title: 比较不同值
challengeType: 1
videoUrl: 'https://scrimba.com/c/cm8PqCa'
forumTopicId: 301174
@ -9,44 +9,42 @@ 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**
**示例**
`3 == '3'` 返回 `true` ,因为 JavaScript 执行了从字符串到数字类型的转换。 `3 === '3'` 返回 false因为类型不同且类型转换没有执行。
**提示** 在 JavaScript 中,你可以使用 `typeof` 运算符确定变量或值的类型,如下所示:
```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
typeof 3
typeof '3'
```
**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'
typeof '3' // returns 'string'
```
`typeof 3` 返回字符串 `number``typeof '3'` 返回字符串 `string`
# --instructions--
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.
编辑器中的 `compareEquality` 函数使用相等运算符比较两个值。 修改函数,使其仅在值严格相等时返回 `Equal`
# --hints--
`compareEquality(10, "10")` should return "Not Equal"
`compareEquality(10, "10")` 应该返回字符串 `Not Equal`
```js
assert(compareEquality(10, '10') === 'Not Equal');
```
`compareEquality("20", 20)` should return "Not Equal"
`compareEquality("20", 20)` 应该返回字符串 `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: Profile Lookup
title: 资料查找
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.
我们有一个对象数组,里面存储着通讯录。
A `lookUpProfile` function that takes `name` and a property (`prop`) as arguments has been pre-written for you.
`lookUpProfile` 函数已经写好了参数,需要 `name` 和属性 (`prop`) 参数。
The function should check if `name` is an actual contact's `firstName` and the given property (`prop`) is a property of that contact.
函数将会检查通讯录中是否存在一个 `firstName` 与传入的 `name` 相同的联系人。 如果存在,那么还需要检查对应的联系人中是否存在 `prop` 属性。
If both are true, then return the "value" of that property.
如果它们都存在,函数返回 prop 属性对应的值。
If `name` does not correspond to any contacts then return `"No such contact"`.
如果 `name` 不对应于任何联系人,然后返回字符串 `No such contact`
If `prop` does not correspond to any valid properties of a contact found to match `name` then return `"No such property"`.
如果 `prop` 属性在匹配 `name` 的联系人里不存在,返回 `No such property`
# --hints--
`lookUpProfile("Kristian", "lastName")` should return `"Vos"`
`lookUpProfile("Kristian", "lastName")` 应该返回字符串 `Vos`
```js
assert(lookUpProfile('Kristian', 'lastName') === 'Vos');
```
`lookUpProfile("Sherlock", "likes")` should return `["Intriguing Cases", "Violin"]`
`lookUpProfile("Sherlock", "likes")` 应该返回 `["Intriguing Cases", "Violin"]`
```js
assert.deepEqual(lookUpProfile('Sherlock', 'likes'), [
@ -38,25 +38,25 @@ assert.deepEqual(lookUpProfile('Sherlock', 'likes'), [
]);
```
`lookUpProfile("Harry", "likes")` should return an array
`lookUpProfile("Harry", "likes")` 应该返回一个数组
```js
assert(typeof lookUpProfile('Harry', 'likes') === 'object');
```
`lookUpProfile("Bob", "number")` should return "No such contact"
`lookUpProfile("Bob", "number")` 应该返回字符串 `No such contact`
```js
assert(lookUpProfile('Bob', 'number') === 'No such contact');
```
`lookUpProfile("Bob", "potato")` should return "No such contact"
`lookUpProfile("Bob", "potato")` 应该返回字符串 `No such contact`
```js
assert(lookUpProfile('Bob', 'potato') === 'No such contact');
```
`lookUpProfile("Akira", "address")` should return "No such property"
`lookUpProfile("Akira", "address")` 应该返回字符串 `No such property`
```js
assert(lookUpProfile('Akira', 'address') === 'No such property');

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244cf
title: Record Collection
title: 记录集合
challengeType: 1
forumTopicId: 18261
dashedName: record-collection
@ -8,21 +8,21 @@ dashedName: record-collection
# --description--
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.
给定一个 JSON 对象,用来表示部分音乐专辑收藏。 每张专辑都有几个属性和一个唯一的 id 号作为键值。 并非所有专辑都有完整的信息。
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.
`updateRecords` 函数开使,这个函数需要一个对象如 `collection`,一个 `id`,一个 `prop` ( `artist` `tracks`), `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` 并且 `value` 不是一个空字符串, 将相册的 `prop` 更新或设置为 `value`
- 如果 `prop` `tracks` 但专辑没有 `tracks` 属性,则应创建空数组并为其添加 `value`
- 如果 `prop` `tracks` 并且 `value` 不是一个空字符串,将 `value` 添加到相册现有 `tracks` 数组的末尾。
- 如果 `value` 是空字符串,从专辑里删除指定的 `prop`
**Note:** A copy of the `collection` object is used for the tests.
**注意:**`collection` 对象做为测试参数对象。
# --hints--
After `updateRecords(collection, 5439, "artist", "ABBA")`, `artist` should be `ABBA`
执行 `updateRecords(collection, 5439, "artist", "ABBA")`, `artist` 应该是字符串 `ABBA`
```js
assert(
@ -31,7 +31,7 @@ assert(
);
```
After `updateRecords(collection, 5439, "tracks", "Take a Chance on Me")`, `tracks` should have `Take a Chance on Me` as the last element.
执行 `updateRecords(collection, 5439, "tracks", "Take a Chance on Me")` 后,`tracks` 的最后一个元素应该为字符串 `Take a Chance on Me`
```js
assert(
@ -41,14 +41,14 @@ assert(
);
```
After `updateRecords(collection, 2548, "artist", "")`, `artist` should not be set
执行 `updateRecords(collection, 2548, "artist", "")` 后, `artist` 不应被设置
```js
updateRecords(_recordCollection, 2548, 'artist', '');
assert(!_recordCollection[2548].hasOwnProperty('artist'));
```
After `updateRecords(collection, 1245, "tracks", "Addicted to Love")`, `tracks` should have `Addicted to Love` as the last element.
执行 `updateRecords(collection, 1245, "tracks", "Addicted to Love")` 后,`tracks` 的最后一个元素应该为字符串 `Addicted to Love`
```js
assert(
@ -58,7 +58,7 @@ assert(
);
```
After `updateRecords(collection, 2468, "tracks", "Free")`, `tracks` should have `1999` as the first element.
执行 `updateRecords(collection, 2468, "tracks", "Free")` 后,`tracks` 的第一个元素应该为字符串 `1999`
```js
assert(
@ -68,14 +68,14 @@ assert(
);
```
After `updateRecords(collection, 2548, "tracks", "")`, `tracks` should not be set
执行 `updateRecords(collection, 2548, "tracks", "")` 后, `tracks` 不应被设置
```js
updateRecords(_recordCollection, 2548, 'tracks', '');
assert(!_recordCollection[2548].hasOwnProperty('tracks'));
```
After `updateRecords(collection, 1245, "albumTitle", "Riptide")`, `albumTitle` should be `Riptide`
执行 `updateRecords(collection, 1245, "albumTitle", "Riptide")`, `albumTitle` 应该是字符串 `Riptide`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5cfa3679138e7d9595b9d9d4
title: Replace Loops using Recursion
title: 使用递归代替循环
challengeType: 1
videoUrl: >-
https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/
@ -10,7 +10,7 @@ dashedName: replace-loops-using-recursion
# --description--
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:
递归是函数调用自身的操作。 为了便于理解,有如下任务:计算数组内元素前 `n` 的元素乘积。 使用 `for` 循环, 可以这样做:
```js
function multiply(arr, n) {
@ -22,7 +22,7 @@ Recursion is the concept that a function can be expressed in terms of itself. To
}
```
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.
下面是递归写法,注意代码里的 `multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]`。 这意味着可以重写 `multiply` 以调用自身而无需依赖循环。
```js
function multiply(arr, n) {
@ -34,35 +34,35 @@ However, notice that `multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]`. Th
}
```
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.
递归版本的 `multiply` 详述如下。 在 <dfn>base case</dfn> 里,也就是 `n <= 0` 时,返回 1。 在 `n` 比 0 大的情况里,函数会调用自身,参数 n 的值为 `n - 1`。 函数以相同的方式持续调用 `multiply`,直到 `n <= 0` 为止。 所以,所有函数都可以返回,原始的 `multiply` 返回结果。
**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.
**注意:** 递归函数在没有函数调用时(在这个例子是,是当 `n <= 0` 时)必需有一个跳出结构,否则永远不会执行完毕。
# --instructions--
Write a recursive function, `sum(arr, n)`, that returns the sum of the first `n` elements of an array `arr`.
写一个递归函数,`sum(arr, n)`,返回递归调用数组 `arr` 从前 `n` 个元素和。
# --hints--
`sum([1], 0)` should equal 0.
`sum([1], 0)` 应该返回 0 。
```js
assert.equal(sum([1], 0), 0);
```
`sum([2, 3, 4], 1)` should equal 2.
`sum([2, 3, 4], 1)` 应该返回 2 。
```js
assert.equal(sum([2, 3, 4], 1), 2);
```
`sum([2, 3, 4, 5], 3)` should equal 9.
`sum([2, 3, 4, 5], 3)` 应该等于 9
```js
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`.).
代码不能包含任意形式的循环(`for``while` 或者高阶函数如:`forEach``map``filter` 以及 `reduce`)。
```js
assert(
@ -72,7 +72,7 @@ assert(
);
```
You should use recursion to solve this problem.
应该用递归解决这个问题。
```js
assert(

View File

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

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244c2
title: Return a Value from a Function with Return
title: 使用 return 给函数返回值
challengeType: 1
videoUrl: 'https://scrimba.com/c/cy87wue'
forumTopicId: 18271
@ -9,44 +9,46 @@ dashedName: return-a-value-from-a-function-with-return
# --description--
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.
我们可以通过函数的参数(<dfn>arguments</dfn>)把值传入函数, 也可以使用 `return` 语句把数据从一个函数中传出来。
**Example**
**示例**
```js
function plusThree(num) {
return num + 3;
}
var answer = plusThree(5); // 8
var answer = plusThree(5);
```
`plusThree` takes an <dfn>argument</dfn> for `num` and returns a value equal to `num + 3`.
`answer` 的值为 `8`
`plusThree` 带有一个参数(<dfn>argument</dfn>`num`并返回return一个等于 `num + 3` 的值。
# --instructions--
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.
创建一个函数 `timesFive` 接收一个参数,把它乘以 `5` 之后返回。
# --hints--
`timesFive` should be a function
`timesFive` 应是一个函数
```js
assert(typeof timesFive === 'function');
```
`timesFive(5)` should return `25`
`timesFive(5)` 应该返回 `25`
```js
assert(timesFive(5) === 25);
```
`timesFive(2)` should return `10`
`timesFive(2)` 应该返回 `10`
```js
assert(timesFive(2) === 10);
```
`timesFive(0)` should return `0`
`timesFive(0)` 应该返回 `0`
```js
assert(timesFive(0) === 0);
@ -55,7 +57,9 @@ assert(timesFive(0) === 0);
# --seed--
## --seed-contents--
```js
```
# --solutions--

View File

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

View File

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

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244dd
title: Selecting from Many Options with Switch Statements
title: 使用 Switch 语句从许多选项中进行选择
challengeType: 1
videoUrl: 'https://scrimba.com/c/c4mv4fm'
forumTopicId: 18277
@ -9,9 +9,9 @@ dashedName: selecting-from-many-options-with-switch-statements
# --description--
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.
如果你有非常多的选项需要选择,可以使用 <dfn>switch</dfn> 语句。 `switch` 评估一个表达式,将表达式的值与 <dfn>case</dfn> 子句匹配。 从第一个匹配的 `case` 值执行语句,直到遇到 `break`
Here is an example of a `switch` statement:
这是 `switch` 语句的示例:
```js
switch(lowercaseLetter) {
@ -24,49 +24,49 @@ switch(lowercaseLetter) {
}
```
`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.
测试 `case` 值使用严格相等(`===`)运算符进行比较。 `break` 告诉 JavaScript 停止执行 switch 语句。 如果遗漏了 `break` ,下一个语句将会被执行。
# --instructions--
Write a switch statement which tests `val` and sets `answer` for the following conditions:
`1` - "alpha"
`2` - "beta"
`3` - "gamma"
`4` - "delta"
写一个测试 `val` 的 switch 语句,并且根据下面的条件来设置不同的 `answer`
`1` - `alpha`
`2` - `beta`
`3` - `gamma`
`4` - `delta`
# --hints--
`caseInSwitch(1)` should have a value of "alpha"
`caseInSwitch(1)` 值应该为字符串 `alpha`
```js
assert(caseInSwitch(1) === 'alpha');
```
`caseInSwitch(2)` should have a value of "beta"
`caseInSwitch(2)` 值应该为字符串 `beta`
```js
assert(caseInSwitch(2) === 'beta');
```
`caseInSwitch(3)` should have a value of "gamma"
`caseInSwitch(3)` 值应该为字符串 `gamma`
```js
assert(caseInSwitch(3) === 'gamma');
```
`caseInSwitch(4)` should have a value of "delta"
`caseInSwitch(4)` 值应该为字符串 `delta`
```js
assert(caseInSwitch(4) === 'delta');
```
You should not use any `if` or `else` statements
不能使用任何 `if` `else` 表达式
```js
assert(!/else/g.test(code) || !/if/g.test(code));
```
You should have at least 3 `break` statements
你应该有至少 3 个 `break` 表达式
```js
assert(code.match(/break/g).length > 2);

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244bc
title: Shopping List
title: 购物清单
challengeType: 1
videoUrl: 'https://scrimba.com/c/c9MEKHZ'
forumTopicId: 18280
@ -9,35 +9,35 @@ dashedName: shopping-list
# --description--
Create a shopping list in the variable `myList`. The list should be a multi-dimensional array containing several sub-arrays.
创建一个名叫 `myList` 的购物清单。 清单的数据格式就是多维数组。
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]`
There should be at least 5 sub-arrays in the list.
任务:你的购物清单至少应该有 5 个子数组。
# --hints--
`myList` should be an array.
`myList` 应该是一个数组
```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);
```
You should have at least 5 items in your list.
你的列表中至少要包含 5 个元素
```js
assert(count > 4);

View File

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

View File

@ -1,6 +1,6 @@
---
id: bd7993c9c69feddfaeb8bdef
title: Store Multiple Values in one Variable using JavaScript Arrays
title: 使用 JavaScript 数组将多个值存储在一个变量中
challengeType: 1
videoUrl: 'https://scrimba.com/c/crZQWAm'
forumTopicId: 18309
@ -9,34 +9,31 @@ 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.
使用数组(`array`),我们可以在一个地方存储多个数据。
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"]`.
`var sandwich = ["peanut butter", "jelly", "bread"]`
# --instructions--
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.
创建一个包含字符串(`string`)和数字( `number`)(按照字符串和数字的顺序)的数组`myArray`
# --hints--
`myArray` should be an `array`.
`myArray`应该是一个数组(`array`)。
```js
assert(typeof myArray == 'object');
```
The first item in `myArray` should be a `string`.
`myArray` 数组的第一个元素应该是一个字符串(`string`)。
```js
assert(typeof myArray[0] !== 'undefined' && typeof myArray[0] == 'string');
```
The second item in `myArray` should be a `number`.
`myArray` 数组的第二个元素应该是一个数字(`number`)。
```js
assert(typeof myArray[1] !== 'undefined' && typeof myArray[1] == 'number');

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244a8
title: Storing Values with the Assignment Operator
title: 使用赋值运算符存储值
challengeType: 1
videoUrl: 'https://scrimba.com/c/cEanysE'
forumTopicId: 18310
@ -9,34 +9,34 @@ dashedName: storing-values-with-the-assignment-operator
# --description--
In JavaScript, you can store a value in a variable with the <dfn>assignment</dfn> operator (`=`).
JavaScript 中,你可以使用赋值(<dfn>assignment</dfn>)运算符 `=`)将值存储在变量中。
`myVariable = 5;`
This assigns the `Number` value `5` to `myVariable`.
这条语句把 `Number` 类型的值 `5` 赋给变量 `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;
```
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`.
首先,此代码创建一个名为 `myVar` 的变量。 数值 `5` 被赋给变量 `myVar`。 现在,如果 `myVar` 再次出现在代码中,程序将会将它视为 `5`
# --instructions--
Assign the value `7` to variable `a`.
把数值 `7` 赋给变量 `a`
# --hints--
You should not change code above the specified comment.
你不应该修改注释上面的代码。
```js
assert(/var a;/.test(code));
```
`a` should have a value of 7.
`a` 的值应该为 7
```js
assert(typeof a === 'number' && a === 7);

View File

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

View File

@ -1,6 +1,6 @@
---
id: 567af2437cbaa8c51670a16c
title: Testing Objects for Properties
title: 测试对象的属性
challengeType: 1
videoUrl: 'https://scrimba.com/c/c6Wz4ySr'
forumTopicId: 18324
@ -9,26 +9,28 @@ dashedName: testing-objects-for-properties
# --description--
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.
有时检查一个对象属性是否存在是非常有用的。 我们可以用对象的 `.hasOwnProperty(propname)` 方法来检查对象是否有指定的属性。 `.hasOwnProperty()` 找到该属性时返回 `true`,找不到该属性时返回 `false`
**Example**
**示例**
```js
var myObj = {
top: "hat",
bottom: "pants"
};
myObj.hasOwnProperty("top"); // true
myObj.hasOwnProperty("middle"); // false
myObj.hasOwnProperty("top");
myObj.hasOwnProperty("middle");
```
第一个 `hasOwnProperty` 返回 `true`,第二个返回 `false`
# --instructions--
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"`.
修改函数 `checkObj` 检查 `obj` 是否有 `checkProp` 属性。 如果属性存在,返回属性对应的值。 如果不存在,返回`"Not Found"`
# --hints--
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift")` should return `"pony"`.
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift")` 应该返回字符串 `pony`
```js
assert(
@ -36,7 +38,7 @@ assert(
);
```
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "pet")` should return `"kitten"`.
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "pet")` 应该返回字符串 `kitten`
```js
assert(
@ -44,7 +46,7 @@ assert(
);
```
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "house")` should return `"Not Found"`.
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "house")` 应该返回字符串 `Not Found`
```js
assert(
@ -53,19 +55,19 @@ assert(
);
```
`checkObj({city: "Seattle"}, "city")` should return `"Seattle"`.
`checkObj({city: "Seattle"}, "city")` 应该返回字符串 `Seattle`
```js
assert(checkObj({ city: 'Seattle' }, 'city') === 'Seattle');
```
`checkObj({city: "Seattle"}, "district")` should return `"Not Found"`.
`checkObj({city: "Seattle"}, "district")` 应该返回字符串 `Not Found`
```js
assert(checkObj({ city: 'Seattle' }, 'district') === 'Not Found');
```
`checkObj({pet: "kitten", bed: "sleigh"}, "gift")` should return `"Not Found"`.
`checkObj({pet: "kitten", bed: "sleigh"}, "gift")` 应该返回字符串 `Not Found`
```js
assert(checkObj({ pet: 'kitten', bed: 'sleigh' }, 'gift') === 'Not Found');

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244ba
title: Understand String Immutability
title: 了解字符串的不变性
challengeType: 1
videoUrl: 'https://scrimba.com/c/cWPVaUR'
forumTopicId: 18331
@ -9,16 +9,16 @@ dashedName: understand-string-immutability
# --description--
In JavaScript, `String` values are <dfn>immutable</dfn>, which means that they cannot be altered once created.
JavaScript 中,字符串(`String`)的值是不可变的(<dfn>immutable</dfn>),这意味着一旦字符串被创建就不能被改变。
For example, the following code:
例如,下面的代码:
```js
var myStr = "Bob";
myStr[0] = "J";
```
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:
是不会把变量 `myStr` 的值改变成 `Job` 的,因为变量 `myStr` 是不可变的。 注意,这*并不*意味着 `myStr` 永远不能被改变,只是字符串字面量 <dfn>string literal</dfn> 的各个字符不能被改变。 改变 `myStr` 的唯一方法是重新给它赋一个值,例如:
```js
var myStr = "Bob";
@ -27,17 +27,17 @@ myStr = "Job";
# --instructions--
Correct the assignment to `myStr` so it contains the string value of `Hello World` using the approach shown in the example above.
更正对 `myStr` 的分配,使用上面示例中的方法包含 `Hello World` 字符串。
# --hints--
`myStr` should have a value of `Hello World`.
`myStr` 的值应该是字符串 `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: Understanding Boolean Values
title: 理解布尔值
challengeType: 1
videoUrl: 'https://scrimba.com/c/c9Me8t4'
forumTopicId: 301176
@ -9,24 +9,23 @@ dashedName: understanding-boolean-values
# --description--
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.
另一种数据类型是布尔(<dfn>Boolean</dfn>)。 布尔值只能是两个值中的一个:`true` 或者 `false`。 它非常像电路开关,`true` 是 “开”,`false` 是 “关”。 这两种状态是互斥的。
**Note**
`Boolean` values are never written with quotes. The `strings` `"true"` and `"false"` are not `Boolean` and have no special meaning in JavaScript.
**注意:**布尔值是不带引号的。 字符串 `"true"``"false"` 不是布尔值,在 JavaScript 中也没有特殊含义。
# --instructions--
Modify the `welcomeToBooleans` function so that it returns `true` instead of `false` when the run button is clicked.
修改 `welcomeToBooleans` 函数,当 run 按钮点击时让它返回 `true` 而不是 `false`
# --hints--
The `welcomeToBooleans()` function should return a boolean (true/false) value.
`welcomeToBooleans()` 函数应该返回一个布尔值 `true` 或者 `false`)。
```js
assert(typeof welcomeToBooleans() === 'boolean');
```
`welcomeToBooleans()` should return true.
`welcomeToBooleans()` 应该返回 `true`
```js
assert(welcomeToBooleans() === true);

View File

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

View File

@ -1,6 +1,6 @@
---
id: 598e8944f009e646fc236146
title: Understanding Undefined Value returned from a Function
title: 函数也可以返回 undefined
challengeType: 1
videoUrl: 'https://scrimba.com/c/ce2p7cL'
forumTopicId: 301177
@ -9,45 +9,45 @@ dashedName: understanding-undefined-value-returned-from-a-function
# --description--
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`.
函数一般用 `return` 语句来返回值,但这不是必须的。 在函数没有 `return` 语句的情况下,当你调用它时,该函数会执行内部代码,返回的值是 `undefined`
**Example**
**示例**
```js
var sum = 0;
function addSum(num) {
sum = sum + num;
}
addSum(3); // sum will be modified but returned value is undefined
addSum(3);
```
`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`.
`addSum` 是一个没有 `return` 语句的函数。 该函数将更改全局变量 `sum`,函数的返回值为 `undefined`
# --instructions--
Create a function `addFive` without any arguments. This function adds 5 to the `sum` variable, but its returned value is `undefined`.
创建一个没有任何参数的函数 `addFive`。 此函数使 `sum` 变量加 5但其返回值是 `undefined`
# --hints--
`addFive` should be a function.
`addFive` 应该是一个函数。
```js
assert(typeof addFive === 'function');
```
Once both functions have ran, the `sum` should be equal to 8.
两个函数运行后,`sum` 应该等于 `8`
```js
assert(sum === 8);
```
Returned value from `addFive` should be `undefined`.
`addFive` 的返回值应该是 `undefined`
```js
assert(addFive() === undefined);
```
Inside the `addFive` function, you should add `5` to the `sum` variable.
`addFive` 函数中,应该给 `sum` 变量增加 `5`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244aa
title: Understanding Uninitialized Variables
title: 理解未初始化的变量
challengeType: 1
videoUrl: 'https://scrimba.com/c/cBa2JAL'
forumTopicId: 18335
@ -9,33 +9,33 @@ dashedName: understanding-uninitialized-variables
# --description--
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"`.
JavaScript 中的变量被声明的时候,程序内部会给它一个初始值 `undefined`。 当你对一个值为 `undefined` 的变量进行运算操作的时候,算出来的结果将会是 `NaN`,它的意思是 <dfn>"Not a Number"</dfn>。 当你用一个值是 `undefined` 的变量来做字符串拼接操作的时候,它会转换成字符串(<dfn>string</dfn>`undefined`
# --instructions--
Initialize the three variables `a`, `b`, and `c` with `5`, `10`, and `"I am a"` respectively so that they will not be `undefined`.
定义 3 个变量 `a``b``c`,并且分别给他们赋值:`5``10``"I am a"`,这样它们值就不会是 `undefined` 了。
# --hints--
`a` should be defined and evaluated to have the value of `6`.
`a` 应该被定义,并且值为 `6`
```js
assert(typeof a === 'number' && a === 6);
```
`b` should be defined and evaluated to have the value of `15`.
`b` 应该被定义,并且值为 `15`
```js
assert(typeof b === 'number' && b === 15);
```
`c` should not contain `undefined` and should have a value of "I am a String!"
`c` 的值不能包含 `undefined`,应该为字符串 `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(

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