diff --git a/curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/nest-an-anchor-element-within-a-paragraph.md b/curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/nest-an-anchor-element-within-a-paragraph.md index 2f7c2ae759..448920a432 100644 --- a/curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/nest-an-anchor-element-within-a-paragraph.md +++ b/curriculum/challenges/chinese/01-responsive-web-design/basic-html-and-html5/nest-an-anchor-element-within-a-paragraph.md @@ -29,7 +29,7 @@ dashedName: nest-an-anchor-element-within-a-paragraph ` ... ` -`a` 元素内的内容文本 `link to freecodecamp.org` 叫作 `anchor text`(锚文本),会显示为一个可以点击的链接: +`a` 元素内的文本 `link to freecodecamp.org` 叫作锚文本,会显示为一个可以点击的链接: `link to freecodecamp.org` @@ -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` 元素中 应包含文本 `View more`。 +`a` 元素应该有文本 `View more`。 ```js assert( @@ -96,7 +104,7 @@ assert( ); ``` -确保每个 `p` 元素有结束标签。 +每个 `p` 元素都应该有一个结束标签。 ```js assert( @@ -106,7 +114,7 @@ assert( ); ``` -确保每个 `a` 元素有结束标签。 +每个 `a` 元素都应该有一个结束标签。 ```js assert( diff --git a/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-personal-portfolio-webpage.md b/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-personal-portfolio-webpage.md index 081b12cbe6..2b5444a94d 100644 --- a/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-personal-portfolio-webpage.md +++ b/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-personal-portfolio-webpage.md @@ -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`。 +你可以使用这个 CodePen 模版创建你自己的项目,点击 `Save` 即可创建你的新项目。 也可以使用此 CDN 链接在任何你喜欢的环境中运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 完成项目并通过所有测试后,请输入你的项目在 CodePen 上的链接并提交。 diff --git a/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-product-landing-page.md b/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-product-landing-page.md index 4a9e50a199..8da6213aa9 100644 --- a/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-product-landing-page.md +++ b/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-product-landing-page.md @@ -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`。 +你可以使用这个 CodePen 模版创建你自己的项目,点击 `Save` 即可创建你的新项目。 也可以使用此 CDN 链接在任何你喜欢的环境中运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 完成项目并通过所有测试后,请输入你的项目在 CodePen 上的链接并提交。 diff --git a/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-survey-form.md b/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-survey-form.md index fba3d99267..544c2494fc 100644 --- a/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-survey-form.md +++ b/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-survey-form.md @@ -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`。 +你可以使用这个 CodePen 模版创建你自己的项目,点击 `Save` 即可创建你的新项目。 也可以使用此 CDN 链接在任何你喜欢的环境中运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 完成项目并通过所有测试后,请输入你的项目在 CodePen 上的链接并提交。 diff --git a/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-technical-documentation-page.md b/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-technical-documentation-page.md index 71c4636642..b16d78431d 100644 --- a/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-technical-documentation-page.md +++ b/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-technical-documentation-page.md @@ -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`。 +你可以使用这个 CodePen 模版创建你自己的项目,点击 `Save` 即可创建你的新项目。 也可以使用此 CDN 链接在任何你喜欢的环境中运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 完成项目并通过所有测试后,请输入你的项目在 CodePen 上的链接并提交。 diff --git a/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-tribute-page.md b/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-tribute-page.md index 683a16da15..7c57480657 100644 --- a/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-tribute-page.md +++ b/curriculum/challenges/chinese/01-responsive-web-design/responsive-web-design-projects/build-a-tribute-page.md @@ -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`。 +你可以使用这个 CodePen 模版创建你的新项目,点击 `Save` 即可创建你的新项目。 也可以使用此 CDN 链接在任何你喜欢的环境中运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 完成项目并通过所有测试后,请输入你的项目在 CodePen 上的链接并提交。 diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/add-items-using-splice.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/add-items-using-splice.md index 04a8878555..e3ae163d15 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/add-items-using-splice.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/add-items-using-splice.md @@ -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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/add-key-value-pairs-to-javascript-objects.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/add-key-value-pairs-to-javascript-objects.md index f5adc6e51b..ae4df94507 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/add-key-value-pairs-to-javascript-objects.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/add-key-value-pairs-to-javascript-objects.md @@ -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 key-value pairs. In other words, they are pieces of data (values) mapped to unique identifiers called properties (keys). Take a look at an example: +对象(object)本质上是键值对(key-value pair)的集合。 或者说,一系列被映射到唯一标识符的数据就是对象;习惯上,唯一标识符叫做属性(property)或者键(key);数据叫做值(value)。 让我们来看一个简单的例子: ```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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/check-for-the-presence-of-an-element-with-indexof.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/check-for-the-presence-of-an-element-with-indexof.md index 4bc028927f..8dc1e7c888 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/check-for-the-presence-of-an-element-with-indexof.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/check-for-the-presence-of-an-element-with-indexof.md @@ -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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/check-if-an-object-has-a-property.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/check-if-an-object-has-a-property.md index e2ac0392eb..31073bbc4e 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/check-if-an-object-has-a-property.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/check-if-an-object-has-a-property.md @@ -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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/combine-arrays-with-the-spread-operator.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/combine-arrays-with-the-spread-operator.md index 0a27f7bb09..a52ac332b2 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/combine-arrays-with-the-spread-operator.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/combine-arrays-with-the-spread-operator.md @@ -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 spread 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: +展开语法(spread)的另一个重要用途是合并数组,或者将某个数组的所有元素插入到另一个数组的任意位置。 我们也可以使用 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 spread operator so that it returns the array `['learning', 'to', 'code', 'is', 'fun']`. +我们已经定义了一个返回 `sentence` 变量的 `spreadOut` 函数。 请修改这个函数,利用 spread 使该函数返回数组 `['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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/copy-an-array-with-the-spread-operator.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/copy-an-array-with-the-spread-operator.md index ca3aa490b5..e8f601ffc3 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/copy-an-array-with-the-spread-operator.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/copy-an-array-with-the-spread-operator.md @@ -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 spread operator 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 中又引入了一个简洁且可读性强的语法:展开运算符(spread operator),它能让我们方便地复制数组中的*所有*元素。 展开语法写出来是这样:`...` -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/)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/copy-array-items-using-slice.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/copy-array-items-using-slice.md index 54ba5bade9..8b90badcd0 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/copy-array-items-using-slice.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/copy-array-items-using-slice.md @@ -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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/create-complex-multi-dimensional-arrays.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/create-complex-multi-dimensional-arrays.md index d15e24bcd4..fdf3161b6f 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/create-complex-multi-dimensional-arrays.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/create-complex-multi-dimensional-arrays.md @@ -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 Objects, lets take one more look, and see how arrays can become a bit more complex than what we have seen in previous challenges. +很好! 你现在已经学到很多关于数组的知识了, 但这些只是个开始。我们将在接下来的中挑战中学到更多与数组相关的知识。 在继续学习对象(Objects)之前,让我们再花一点时间了解下更复杂的数组嵌套。 -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 multi-dimensional, or nested array. Consider the following example: +数组的一个强大的特性是,它可以包含其他数组,甚至完全由其他数组组成。 在上一个挑战中,我们已经接触到了包含数组的数组,但它还算是比较简单的。 数组中的数组还可以再包含其他数组,即可以嵌套任意多层数组。 习惯上,我们称这种数据结构为多维(multi-dimensional)数组或嵌套(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 strings, numbers, and booleans 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`,使用字符串(string)、数字(number)或布尔值(boolean)的任意组合作为数组的元素,并让 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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops.md index 6674711f21..7e6d865dfb 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops.md @@ -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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-the-keys-of-an-object-with-a-for...in-statement.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-the-keys-of-an-object-with-a-for...in-statement.md index 390132b504..f59f9f6fac 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-the-keys-of-an-object-with-a-for...in-statement.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-the-keys-of-an-object-with-a-for...in-statement.md @@ -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 for...in statement. For our `users` object, this could look like: +如果我们想要遍历对象中的所有属性, 只需要使用 JavaScript 中的 for...in 语句即可。 以遍历 `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 for...in 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 对象参数。 请在其中使用 for...in 语句来遍历传入函数的 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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/remove-items-from-an-array-with-pop-and-shift.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/remove-items-from-an-array-with-pop-and-shift.md index 9cb6b79038..4d7402fb85 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/remove-items-from-an-array-with-pop-and-shift.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/remove-items-from-an-array-with-pop-and-shift.md @@ -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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/remove-items-using-splice.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/remove-items-using-splice.md index ce579da8e7..f09cad0542 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/remove-items-using-splice.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/remove-items-using-splice.md @@ -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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/use-an-array-to-store-a-collection-of-data.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/use-an-array-to-store-a-collection-of-data.md index 61f8b4f1c3..3ff59662eb 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/use-an-array-to-store-a-collection-of-data.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/use-an-array-to-store-a-collection-of-data.md @@ -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 one-dimensional array, meaning it only has one level, or that it does not have any other arrays nested within it. Notice it contains booleans, strings, and numbers, among other valid JavaScript data types: +以下是最简单的数组(Array)示例: 这是一个一维数组(one-dimensional array),它只有一层,或者说它里面没有包含其它数组。 可以观察到,这个数组中只包含了布尔值(booleans)、字符串(strings)、数字(numbers)以及 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 multi-dimensional array, or an array that contains other arrays. Notice that this array also contains JavaScript objects, 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` 来访问它。 下面是一个关于数组的更复杂的例子。 这是一个多维数组 (multi-dimensional Array),或者说是一个包含了其他数组的数组。 可以注意到,在它的内部还包含了 JavaScript 中的对象(objects)结构。 我们会在后面的小节中讨论该数据结构,但现在你只需要知道数组能够存储复杂的对象类型数据。 ```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 string, one number, and one boolean. +我们已经定义了一个名为 `yourArray` 的变量。 请修改代码,将一个含有至少 5 个元素的数组赋值给 `yourArray` 变量。 你的数组中应包含至少一个 string 类型的数据、一个 number 类型的数据和一个 boolean 类型的数据。 # --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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/access-array-data-with-indexes.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/access-array-data-with-indexes.md index 0a1b708108..cccb75c914 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/access-array-data-with-indexes.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/access-array-data-with-indexes.md @@ -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 indexes. +我们可以使用索引(indexes)来访问数组中的数据。 -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 zero-based indexing, so the first element in an array has an index of `0`. +数组索引与字符串一样使用方括号来表示,不同的是,它们不是指定字符,而是指定数组中的一个条目。 数组索引与字符串索引一样是从 0 开始(zero-based)的,所以数组中第一个元素的索引编号是 `0`。
-**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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/access-multi-dimensional-arrays-with-indexes.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/access-multi-dimensional-arrays-with-indexes.md index d7ca5ed641..19d1f874d9 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/access-multi-dimensional-arrays-with-indexes.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/access-multi-dimensional-arrays-with-indexes.md @@ -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 multi-dimensional array, is as an *array of arrays*. When you use brackets to access your array, the first set of brackets refers to the entries in the outer-most (the first level) array, and each additional pair of brackets refers to the next level of entries inside. +我们可以把多维数组看作成是*数组中的数组*。 使用方括号表示法访问数组时,第一个方括号访问的是数组的最外层(第一层),第二个方括号访问的是数组的第二层,以此类推。 -**Example** +**例如:** ```js var arr = [ @@ -20,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))); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays.md index 59d912c1cf..fcc84457c8 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays.md @@ -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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects.md index d8a7470d1f..db833dd81b 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects.md @@ -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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-bracket-notation.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-bracket-notation.md index a92f2eddcd..db05692570 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-bracket-notation.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-bracket-notation.md @@ -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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-dot-notation.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-dot-notation.md index af90aafcbc..d5663a178b 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-dot-notation.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-dot-notation.md @@ -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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables.md index 05713220d6..728d5170ac 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables.md @@ -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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/add-new-properties-to-a-javascript-object.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/add-new-properties-to-a-javascript-object.md index 975b0206be..9a94ced3b1 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/add-new-properties-to-a-javascript-object.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/add-new-properties-to-a-javascript-object.md @@ -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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/add-two-numbers-with-javascript.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/add-two-numbers-with-javascript.md index 255cd3a3ed..af90b54023 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/add-two-numbers-with-javascript.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/add-two-numbers-with-javascript.md @@ -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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/adding-a-default-option-in-switch-statements.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/adding-a-default-option-in-switch-statements.md index 51b62017b0..98dba35fbd 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/adding-a-default-option-in-switch-statements.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/adding-a-default-option-in-switch-statements.md @@ -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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/appending-variables-to-strings.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/appending-variables-to-strings.md index be826ab034..0795af9b46 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/appending-variables-to-strings.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/appending-variables-to-strings.md @@ -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 literals, we can also append variables to a string using the plus equals (`+=`) operator. +就像我们可以用多行字符串字面量构建单个字符串一样,我们还可以使用加且赋值(`+=`)运算符将字符串追加到字符串的末尾。 -Example: +示例: ```js var anAdjective = "awesome!"; var ourStr = "freeCodeCamp is "; ourStr += anAdjective; -// ourStr 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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/assigning-the-value-of-one-variable-to-another.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/assigning-the-value-of-one-variable-to-another.md index 2938f087ee..1a756600d9 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/assigning-the-value-of-one-variable-to-another.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/assigning-the-value-of-one-variable-to-another.md @@ -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 assignment operator, you can assign the value of that variable to another variable using the assignment operator. +在使用赋值运算符赋予变量某个值后,你可以使用赋值运算符将该变量的值赋给另一个变量。 ```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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/build-javascript-objects.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/build-javascript-objects.md index 9289d9ff58..4ecd72ba0e 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/build-javascript-objects.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/build-javascript-objects.md @@ -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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/chaining-if-else-statements.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/chaining-if-else-statements.md index f68a2f94db..343184029d 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/chaining-if-else-statements.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/chaining-if-else-statements.md @@ -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 pseudocode of multiple chained `if` / `else if` statements: +`if/else` 语句串联在一起可以实现复杂的逻辑。 这是多个 `if` / `else if` 语句串联在一起的伪代码: ```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'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comment-your-javascript-code.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comment-your-javascript-code.md index e828a1ba0e..50271224d6 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comment-your-javascript-code.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comment-your-javascript-code.md @@ -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-- diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator.md index 8fd2086992..8e15f96ca2 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator.md @@ -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 comparison operators in JavaScript. All of these operators return a boolean `true` or `false` value. +在 JavaScript 中,有很多 相互比较的操作。 所有这些操作符都返回一个 `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 data types (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 中,为了让两个不同的数据类型(例如 `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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-greater-than-or-equal-to-operator.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-greater-than-or-equal-to-operator.md index 0cb1d1d46a..739ac0a38c 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-greater-than-or-equal-to-operator.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-greater-than-or-equal-to-operator.md @@ -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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-inequality-operator.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-inequality-operator.md index 24d6c5fbec..e289c41a8c 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-inequality-operator.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-inequality-operator.md @@ -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(/(?!!==)!=/)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-less-than-or-equal-to-operator.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-less-than-or-equal-to-operator.md index 5174b635b4..f8c13e4626 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-less-than-or-equal-to-operator.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-less-than-or-equal-to-operator.md @@ -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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-strict-equality-operator.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-strict-equality-operator.md index b8d73b9aa4..4caaf30c2c 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-strict-equality-operator.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-strict-equality-operator.md @@ -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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-and-operator.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-and-operator.md index bf9c2a6c1a..6dd5f15f24 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-and-operator.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-and-operator.md @@ -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 logical and operator (`&&`) returns `true` if and only if the operands to the left and right of it are true. +有时你需要在一次判断中做多个操作。 当且仅当运算符的左边和右边都是 true,逻辑与运算符(`&&`)才会返回`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'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-or-operator.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-or-operator.md index cd5d09d36f..75679a108a 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-or-operator.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-or-operator.md @@ -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 logical or operator (`||`) returns `true` if either of the operands is `true`. Otherwise, it returns `false`. +只要逻辑或运算符(`||`)两边的任何一个运算的结果是 `true`,则返回 `true`。 否则,返回 `false`。 -The logical or operator is composed of two pipe symbols: (`||`). This can typically be found between your Backspace and Enter keys. +逻辑或运算符由两个竖线(`||`)组成。 这个按键位于退格键和回车键之间。 -The pattern below should look familiar from prior waypoints: +下面这样的语句你应该很熟悉: ```js if (num > 10) { @@ -25,7 +25,7 @@ if (num < 5) { return "Yes"; ``` -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'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-addition.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-addition.md index 0a2ab04992..01e2a687b3 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-addition.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-addition.md @@ -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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/concatenating-strings-with-plus-operator.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/concatenating-strings-with-plus-operator.md index ec94ec73ed..87f55cf977 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/concatenating-strings-with-plus-operator.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/concatenating-strings-with-plus-operator.md @@ -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 concatenation operator. You can build a new string out of other strings by concatenating them together. +在 JavaScript 中,当 `+` 操作符被用于一个 `String` 类型的值的时候,它被称作拼接操作符。 你可以通过拼接其他字符串来创建一个新的字符串。 -**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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/concatenating-strings-with-the-plus-equals-operator.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/concatenating-strings-with-the-plus-equals-operator.md index e1bf723545..c963cb952a 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/concatenating-strings-with-the-plus-equals-operator.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/concatenating-strings-with-the-plus-equals-operator.md @@ -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 concatenate a string onto the end of an existing string variable. This can be very helpful to break a long string over several lines. +我们还可以使用 `+=` 运算符来拼接字符串到现有字符串变量的结尾。 对于那些被分割成几段的长的字符串来说,这一操作是非常有用的。 -**Note** -Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself. +**提示:**注意空格。 拼接操作不会在两个字符串之间添加空格,所以,如果想要加上空格的话,你需要自己在字符串里面添加。 -Example: +例如: ```js var ourStr = "I come first. "; ourStr += "I come second."; -// ourStr is now "I come first. I come second." ``` +`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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/constructing-strings-with-variables.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/constructing-strings-with-variables.md index 183aa48865..9c637cd5f3 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/constructing-strings-with-variables.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/constructing-strings-with-variables.md @@ -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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/count-backwards-with-a-for-loop.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/count-backwards-with-a-for-loop.md index 9edc5f1cb9..75e208e5b2 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/count-backwards-with-a-for-loop.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/count-backwards-with-a-for-loop.md @@ -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,我们需要改变 initialization、condition 和 final-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]`。 让我们改变 initialization 和 final-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]); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/counting-cards.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/counting-cards.md index 4d98fdecfb..8de2525b01 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/counting-cards.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/counting-cards.md @@ -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 或负数,玩家应该追加少许赌注甚至不追加赌注。 -
Count ChangeCards
+12, 3, 4, 5, 6
07, 8, 9
-110, 'J', 'Q', 'K', 'A'
+
计数卡牌
+12, 3, 4, 5, 6
07, 8, 9
-110, 'J', 'Q', 'K', 'A'
-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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/create-decimal-numbers-with-javascript.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/create-decimal-numbers-with-javascript.md index de35aa22d3..aa518f3b80 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/create-decimal-numbers-with-javascript.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/create-decimal-numbers-with-javascript.md @@ -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 floating point numbers or floats. +我们也可以把小数存储到变量中。 小数有时候也被称作浮点数或者 floats。 -**Note** -Not all real numbers can accurately be represented in floating point. This can lead to rounding errors. [Details Here](https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems). +**提示:**不是所有的实数都可以用浮点数(floating point)来表示。 因为可能产生四舍五入的错误, [查看详情](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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/declare-string-variables.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/declare-string-variables.md index 440fa546fc..186ea54346 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/declare-string-variables.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/declare-string-variables.md @@ -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 string literal. It is a string because it is a series of zero or more characters enclosed in single or double quotes. +`"your name"` 被称作字符串变量。 字符串是用单引号或双引号包裹起来的一连串的零个或多个字符。 # --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-- diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/decrement-a-number-with-javascript.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/decrement-a-number-with-javascript.md index 2f71a24523..8c68326d8f 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/decrement-a-number-with-javascript.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/decrement-a-number-with-javascript.md @@ -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 decrement or decrease a variable by one with the `--` operator. +使用自减符号`--`,你可以很方便地对一个变量执行自减或者 -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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/delete-properties-from-a-javascript-object.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/delete-properties-from-a-javascript-object.md index 21c8366962..14b01da4ea 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/delete-properties-from-a-javascript-object.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/delete-properties-from-a-javascript-object.md @@ -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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/divide-one-number-by-another-with-javascript.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/divide-one-number-by-another-with-javascript.md index 7cd4e25b80..ac7f518811 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/divide-one-number-by-another-with-javascript.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/divide-one-number-by-another-with-javascript.md @@ -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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/escape-sequences-in-strings.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/escape-sequences-in-strings.md index 700cf22c26..d788266daf 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/escape-sequences-in-strings.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/escape-sequences-in-strings.md @@ -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 escaped inside a string. There are two reasons to use escaping characters: +引号不是字符串中唯一可以被 转义 的字符。 使用转义字符有两个原因: -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. +我们在之前的挑战中学到了这个。 -
CodeOutput
\'single quote
\"double quote
\\backslash
\nnewline
\rcarriage return
\ttab
\bword boundary
\fform feed
+
代码输出
\'单引号
\"双引号
\\反斜杠
\n换行符
\r回车符
\t制表符
\b退格
\f换页符
-*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`。 -
FirstLine
    \SecondLine
ThirdLine
+
FirstLine
\SecondLine
ThirdLine
-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 \\ +`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'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/escaping-literal-quotes-in-strings.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/escaping-literal-quotes-in-strings.md index 9524797b5a..1d46b3083f 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/escaping-literal-quotes-in-strings.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/escaping-literal-quotes-in-strings.md @@ -11,7 +11,7 @@ dashedName: escaping-literal-quotes-in-strings 定义一个字符串必须要用单引号或双引号来包裹它。 那么当你的字符串里面包含引号 `"` 或者 `'` 时该怎么办呢? -在 JavaScript 中,你可以通过在引号前面使用反斜杠\\)来转义引号。 +在 JavaScript 中,可以通过在引号前面使用反斜杠(`\`)来转义引号。 `var sampleStr = "Alan said, \"Peter is learning JavaScript\".";` diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/find-the-length-of-a-string.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/find-the-length-of-a-string.md index 03bc3f0071..71f12117bb 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/find-the-length-of-a-string.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/find-the-length-of-a-string.md @@ -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/)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/finding-a-remainder-in-javascript.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/finding-a-remainder-in-javascript.md index c811162a83..4d7a9b7e34 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/finding-a-remainder-in-javascript.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/finding-a-remainder-in-javascript.md @@ -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 remainder operator `%` gives the remainder of the division of two numbers. +remainder 求余运算符 `%` 返回两个数相除得到的余数 -**Example** +**示例** -
5 % 2 = 1 because
Math.floor(5 / 2) = 2 (Quotient)
2 * 2 = 4
5 - 4 = 1 (Remainder)
+
5 % 2 = 1 因为
Math.floor(5 / 2) = 2 (商)
2 * 2 = 4
5 - 4 = 1 (余数)
-**Usage** -In mathematics, a number can be checked to be even or odd by checking the remainder of the division of the number by `2`. +**用法** +在数学中,判断一个数是奇数还是偶数,只需要判断这个数除以 `2` 得到的余数是 0 还是 1。 -
17 % 2 = 1 (17 is Odd)
48 % 2 = 0 (48 is Even)
+
17 % 2 = 1(17 是奇数)
48 % 2 = 0(48 是偶数)
-**Note** -The remainder operator is sometimes incorrectly referred to as the "modulus" operator. It is very similar to modulus, but does not work properly with negative numbers. +**提示**余数运算符(remainder)有时被错误地称为“模数”运算符。 它与模数非常相似,但不能用于负数的运算。 # --instructions-- -Set `remainder` equal to the remainder of `11` divided by `3` using the remainder (`%`) operator. +使用 remainder (`%`)运算符,计算 `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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-fractions-with-javascript.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-fractions-with-javascript.md index 7565d935ad..9b94dea35c 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-fractions-with-javascript.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-fractions-with-javascript.md @@ -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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/global-vs.-local-scope-in-functions.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/global-vs.-local-scope-in-functions.md index 4aa4e70ab0..502e1a8f49 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/global-vs.-local-scope-in-functions.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/global-vs.-local-scope-in-functions.md @@ -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 local and global variables with the same name. When you do this, the `local` variable takes precedence over the `global` variable. +一个程序中有可能具有相同名称的局部变量 和全局变量。 在这种情况下,`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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/golf-code.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/golf-code.md index c53081daa9..a0a37a2ad4 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/golf-code.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/golf-code.md @@ -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`。 根据下表返回正确的字符串。下表列出不同挥杆次数(从高到低)对应的字符串。 -
StrokesReturn
1"Hole-in-one!"
<= par - 2"Eagle"
par - 1"Birdie"
par"Par"
par + 1"Bogey"
par + 2"Double Bogey"
>= par + 3"Go Home!"
+
挥杆次数返回字符串
1"Hole-in-one!"
<= par - 2"Eagle"
par - 1"Birdie"
par"Par"
par + 1"Bogey"
par + 2"Double Bogey"
>= par + 3"Go Home!"
-`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!'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/increment-a-number-with-javascript.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/increment-a-number-with-javascript.md index f2d9b91295..a771cd0c4b 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/increment-a-number-with-javascript.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/increment-a-number-with-javascript.md @@ -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 increment or add one to a variable with the `++` operator. +使用 `++`,我们可以很容易地对变量进行自增或者 +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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-if-statements.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-if-statements.md index 9ce7a4d8c6..72669d8633 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-if-statements.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-if-statements.md @@ -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'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-statements.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-statements.md index 24e5b17225..3d2d90e45c 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-statements.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-statements.md @@ -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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-odd-numbers-with-a-for-loop.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-odd-numbers-with-a-for-loop.md index bbcc4049a8..6c1426a963 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-odd-numbers-with-a-for-loop.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-odd-numbers-with-a-for-loop.md @@ -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]); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop.md index 9d1ae06aa2..8623890917 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop.md @@ -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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-do...while-loops.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-do...while-loops.md index f4dfc98ba7..725a66d715 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-do...while-loops.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-do...while-loops.md @@ -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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-for-loops.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-for-loops.md index fdd4e3ee80..c5e93aea90 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-for-loops.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-for-loops.md @@ -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]); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-while-loops.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-while-loops.md index 3b9dfd4048..6f573836d0 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-while-loops.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-while-loops.md @@ -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]); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/local-scope-and-functions.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/local-scope-and-functions.md index 14d1ca237c..174d5521b4 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/local-scope-and-functions.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/local-scope-and-functions.md @@ -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 local scope. That means, they are only visible within that function. +在一个函数内声明的变量,以及该函数的参数都具有局部(local)作用域。 这意味着它们只在该函数内可见。 -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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/logical-order-in-if-else-statements.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/logical-order-in-if-else-statements.md index 55c074ae99..1678c4d7ef 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/logical-order-in-if-else-statements.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/logical-order-in-if-else-statements.md @@ -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'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-pop.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-pop.md index ae2cc7fab3..a323de881e 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-pop.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-pop.md @@ -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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-push.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-push.md index b6fcea0681..340f78cebb 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-push.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-push.md @@ -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 parameters and "pushes" them onto the end of the array. +`.push()` 接受一个或多个参数(parameters),并把它压入到数组的末尾。 -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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-shift.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-shift.md index 4a68ea9135..2f578524c5 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-shift.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-shift.md @@ -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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-unshift.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-unshift.md index 39d4b3c002..6d2a5c93b4 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-unshift.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-unshift.md @@ -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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects.md index 61d0af1cda..c3beb55a78 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects.md @@ -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 Data Structure. A JavaScript object is one way to handle flexible data. They allow for arbitrary combinations of strings, numbers, booleans, arrays, functions, and objects. +有时你可能希望将数据存储在一个灵活的数据结构(Data Structure)中。 JavaScript 对象是一种灵活的数据结构。 它可以储存字符串(strings)、数字(numbers)、布尔值(booleans)、数组(arrays)、函数(functions)和对象(objects)以及这些值的任意组合。 -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 metadata 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. +这是一个包含一个对象的数组。 该对象有关于专辑的各种元数据(metadata)。 它也有一个嵌套的 `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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/modify-array-data-with-indexes.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/modify-array-data-with-indexes.md index 86fa3ee5ba..09d6487dd2 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/modify-array-data-with-indexes.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/modify-array-data-with-indexes.md @@ -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 mutable and can be changed freely. +与字符串的数据不可变不同,数组的数据是可变的( mutable),可以自由地改变。 -**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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/multiple-identical-options-in-switch-statements.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/multiple-identical-options-in-switch-statements.md index 72b18e4928..0c0b63f9c1 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/multiple-identical-options-in-switch-statements.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/multiple-identical-options-in-switch-statements.md @@ -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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/multiply-two-numbers-with-javascript.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/multiply-two-numbers-with-javascript.md index 5be738a56f..f0ccb4107a 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/multiply-two-numbers-with-javascript.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/multiply-two-numbers-with-javascript.md @@ -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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/nest-one-array-within-another-array.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/nest-one-array-within-another-array.md index de2c0bbe8d..ac3f1b0fb7 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/nest-one-array-within-another-array.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/nest-one-array-within-another-array.md @@ -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 multi-dimensional array. +这也叫做多维数组(multi-dimensional array)。 # --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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/nesting-for-loops.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/nesting-for-loops.md index 8b9042e06f..aae63715bf 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/nesting-for-loops.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/nesting-for-loops.md @@ -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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/passing-values-to-functions-with-arguments.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/passing-values-to-functions-with-arguments.md index 9c38b815fc..0648e72247 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/passing-values-to-functions-with-arguments.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/passing-values-to-functions-with-arguments.md @@ -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-- -Parameters 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 "passed") into a function when it is called are known as arguments. +函数的参数 (parameters)在函数中充当调用函数时传入函数的输入占位符(也叫形参)的作用。 函数调用时,参数可以为一个或多个。 调用函数时输入(或传递 "passed")的实际值被称为参数(arguments)。 -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-- -
  1. Create a function called functionWithArgs that accepts two arguments and outputs their sum to the dev console.
  2. Call the function with two numbers as arguments.
+
  1. 创建一个名为 functionWithArgs 的函数,它可以接收两个参数,计算参数的和,将结果输出到控制台。
  2. 用两个数字作为参数调用函数。
# --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-- diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/practice-comparing-different-values.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/practice-comparing-different-values.md index c97f6c7eb9..a344ba6879 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/practice-comparing-different-values.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/practice-comparing-different-values.md @@ -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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/profile-lookup.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/profile-lookup.md index 4f2c51e24c..552d0c175d 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/profile-lookup.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/profile-lookup.md @@ -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'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/record-collection.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/record-collection.md index d3335ba646..964baea8de 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/record-collection.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/record-collection.md @@ -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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion.md index 0c060c2bca..faf39d1271 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion.md @@ -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 base case, 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` 详述如下。 在 base case 里,也就是 `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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/replacing-if-else-chains-with-switch.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/replacing-if-else-chains-with-switch.md index e724c8821c..0325d50b49 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/replacing-if-else-chains-with-switch.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/replacing-if-else-chains-with-switch.md @@ -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) === ''); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/return-a-value-from-a-function-with-return.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/return-a-value-from-a-function-with-return.md index 3feb8d7826..fc2cec504e 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/return-a-value-from-a-function-with-return.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/return-a-value-from-a-function-with-return.md @@ -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 arguments. You can use a `return` statement to send a value back out of a function. +我们可以通过函数的参数(arguments)把值传入函数, 也可以使用 `return` 语句把数据从一个函数中传出来。 -**Example** +**示例** ```js function plusThree(num) { return num + 3; } -var answer = plusThree(5); // 8 +var answer = plusThree(5); ``` -`plusThree` takes an argument for `num` and returns a value equal to `num + 3`. +`answer` 的值为 `8`。 + +`plusThree` 带有一个参数(argument)`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-- diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/return-early-pattern-for-functions.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/return-early-pattern-for-functions.md index b51c7ebdb8..07226008ee 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/return-early-pattern-for-functions.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/return-early-pattern-for-functions.md @@ -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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/returning-boolean-values-from-functions.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/returning-boolean-values-from-functions.md index 1aabc48cbe..91253acb1d 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/returning-boolean-values-from-functions.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/returning-boolean-values-from-functions.md @@ -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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/selecting-from-many-options-with-switch-statements.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/selecting-from-many-options-with-switch-statements.md index 3e6c185dd0..3120995b0b 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/selecting-from-many-options-with-switch-statements.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/selecting-from-many-options-with-switch-statements.md @@ -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 switch statement. A `switch` statement tests a value and can have many case statements which define various possible values. Statements are executed from the first matched `case` value until a `break` is encountered. +如果你有非常多的选项需要选择,可以使用 switch 语句。 `switch` 评估一个表达式,将表达式的值与 case 子句匹配。 从第一个匹配的 `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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/shopping-list.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/shopping-list.md index 84f22f2b42..af54d26eab 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/shopping-list.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/shopping-list.md @@ -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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/stand-in-line.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/stand-in-line.md index 1d882d80d6..545ee62d5e 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/stand-in-line.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/stand-in-line.md @@ -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 queue is an abstract Data Structure 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. +在计算机科学中队列(queue)是一个抽象的数据结构(Data Structure),队列中的条目都是有秩序的。 新的条目会被加到队列的末尾,旧的条目会从队列的头部被移出。 -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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/store-multiple-values-in-one-variable-using-javascript-arrays.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/store-multiple-values-in-one-variable-using-javascript-arrays.md index ac96b05987..9b61e8b1c4 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/store-multiple-values-in-one-variable-using-javascript-arrays.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/store-multiple-values-in-one-variable-using-javascript-arrays.md @@ -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'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator.md index b60c20c275..cd5c8444ca 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator.md @@ -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 assignment operator (`=`). +在 JavaScript 中,你可以使用赋值(assignment)运算符 (`=`)将值存储在变量中。 `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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/subtract-one-number-from-another-with-javascript.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/subtract-one-number-from-another-with-javascript.md index e4b1e9c346..ad7eaf40ac 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/subtract-one-number-from-another-with-javascript.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/subtract-one-number-from-another-with-javascript.md @@ -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))); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/testing-objects-for-properties.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/testing-objects-for-properties.md index d6c053d601..88e038081a 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/testing-objects-for-properties.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/testing-objects-for-properties.md @@ -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'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understand-string-immutability.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understand-string-immutability.md index 8a78800648..c33001dd50 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understand-string-immutability.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understand-string-immutability.md @@ -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 immutable, which means that they cannot be altered once created. +在 JavaScript 中,字符串(`String`)的值是不可变的(immutable),这意味着一旦字符串被创建就不能被改变。 -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 string literal cannot be changed. The only way to change `myStr` would be to assign it with a new string, like this: +是不会把变量 `myStr` 的值改变成 `Job` 的,因为变量 `myStr` 是不可变的。 注意,这*并不*意味着 `myStr` 永远不能被改变,只是字符串字面量 string literal 的各个字符不能被改变。 改变 `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)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-boolean-values.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-boolean-values.md index 51208aa42a..acfe53156e 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-boolean-values.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-boolean-values.md @@ -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 Boolean. `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. +另一种数据类型是布尔(Boolean)。 布尔值只能是两个值中的一个:`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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-case-sensitivity-in-variables.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-case-sensitivity-in-variables.md index e7fcb1247b..e3e40f6237 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-case-sensitivity-in-variables.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-case-sensitivity-in-variables.md @@ -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 camelCase. In camelCase, multi-word variable names have the first word in lowercase and the first letter of each subsequent word is capitalized. +使用驼峰命名法(camelCase)来书写一个 Javascript 变量。 在驼峰命名法(camelCase)中,变量名的第一个单词的首写字母小写,后面的单词的第一个字母大写 -**Examples:** +**示例:** ```js var someVariable; @@ -27,18 +27,19 @@ var thisVariableNameIsSoLong; # --instructions-- -Modify the existing declarations and assignments so their names use camelCase. -Do not create any new variables. +修改已声明的变量,让它们的命名符合驼峰命名法(camelCase)的规范。 + +不要创建任何新变量。 # --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); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-undefined-value-returned-from-a-function.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-undefined-value-returned-from-a-function.md index 94aa143e1e..550efd9bab 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-undefined-value-returned-from-a-function.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-undefined-value-returned-from-a-function.md @@ -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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables.md index 3779655066..5644f150a2 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables.md @@ -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 "Not a Number". If you concatenate a string with an `undefined` variable, you will get a literal string of `"undefined"`. +当 JavaScript 中的变量被声明的时候,程序内部会给它一个初始值 `undefined`。 当你对一个值为 `undefined` 的变量进行运算操作的时候,算出来的结果将会是 `NaN`,它的意思是 "Not a Number"。 当你用一个值是 `undefined` 的变量来做字符串拼接操作的时候,它会转换成字符串(string)`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( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/updating-object-properties.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/updating-object-properties.md index fade65082c..10d9d6b255 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/updating-object-properties.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/updating-object-properties.md @@ -1,6 +1,6 @@ --- id: 56bbb991ad1ed5201cd392d1 -title: Updating Object Properties +title: 更新对象属性 challengeType: 1 videoUrl: 'https://scrimba.com/c/c9yEJT4' forumTopicId: 18336 @@ -9,9 +9,9 @@ dashedName: updating-object-properties # --description-- -After you've created a JavaScript object, you can update its properties at any time just like you would update any other variable. You can use either dot or bracket notation to update. +在你创建了 JavaScript 对象后,你可以随时更新它的属性,就像更新任何其他变量那样。 你可以使用点或中括号操作符来更新。 -For example, let's look at `ourDog`: +举个例子,让我们看看 `ourDog`: ```js var ourDog = { @@ -22,21 +22,21 @@ var ourDog = { }; ``` -Since he's a particularly happy dog, let's change his name to "Happy Camper". Here's how we update his object's name property: `ourDog.name = "Happy Camper";` or `ourDog["name"] = "Happy Camper";` Now when we evaluate `ourDog.name`, instead of getting "Camper", we'll get his new name, "Happy Camper". +既然他是一个特别愉快的狗,让我们将他的名字更改为字符串 `Happy Camper`。 这有两种方式来更新对象的 name 属性: `ourDog.name = "Happy Camper";` 或 `ourDog["name"] = "Happy Camper";`。更新后,`ourDog.name` 的值就不再是 `Camper`,而是 `Happy Camper`。 # --instructions-- -Update the `myDog` object's name property. Let's change her name from "Coder" to "Happy Coder". You can use either dot or bracket notation. +更新 `myDog` 对象的 name 属性。 让它的名字从 `Coder` 变成 `Happy Coder`。 你可以使用点号表示法或方括号表示法来完成此挑战。 # --hints-- -You should update `myDog`'s `"name"` property to equal "Happy Coder". +更新 `myDog` 的 `name` 属性,使其等于 `Happy Coder`。 ```js assert(/happy coder/gi.test(myDog.name)); ``` -You should not edit the `myDog` definition. +不要修改 `myDog` 的定义。 ```js assert(/"name": "Coder"/.test(code)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-first-character-in-a-string.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-first-character-in-a-string.md index 78c7bc400d..fd7af9cb36 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-first-character-in-a-string.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-first-character-in-a-string.md @@ -1,6 +1,6 @@ --- id: bd7123c9c549eddfaeb5bdef -title: Use Bracket Notation to Find the First Character in a String +title: 使用方括号查找字符串中的第一个字符 challengeType: 1 videoUrl: 'https://scrimba.com/c/ca8JwhW' forumTopicId: 18341 @@ -9,34 +9,36 @@ dashedName: use-bracket-notation-to-find-the-first-character-in-a-string # --description-- -Bracket notation is a way to get a character at a specific `index` within a string. +方括号表示法(Bracket notation)是一种在字符串中的特定 index(索引)处获取字符的方法。 -Most modern programming languages, like JavaScript, don't start counting at 1 like humans do. They start at 0. This is referred to as Zero-based indexing. +大多数现代编程语言,如JavaScript,不同于人类从 1 开始计数。 它们是从 0 开始计数。 这被称为基于零(Zero-based)的索引。 -For example, the character at index 0 in the word "Charles" is "C". So if `var firstName = "Charles"`, you can get the value of the first letter of the string by using `firstName[0]`. +例如,单词 `Charles` 的索引 0 的字符是 `C`。 所以在 `var firstName = "Charles"` 中,你可以使用 `firstName[0]` 来获得第一个位置上的字符。 -Example: +示例: ```js var firstName = "Charles"; -var firstLetter = firstName[0]; // firstLetter is "C" +var firstLetter = firstName[0]; ``` +`firstLetter` 值为字符串 `C` 。 + # --instructions-- -Use bracket notation to find the first character in the `lastName` variable and assign it to `firstLetterOfLastName`. +使用方括号获取变量 `lastName` 中的第一个字符,并赋给变量 `firstLetterOfLastName`。 -**Hint:** Try looking at the example above if you get stuck. +**提示:** 如果卡住了,请尝试查看上面的示例。 # --hints-- -The `firstLetterOfLastName` variable should have the value of `L`. +`firstLetterOfLastName` 变量值应该为 `L` 。 ```js assert(firstLetterOfLastName === 'L'); ``` -You should use bracket notation. +应该使用方括号表示法。 ```js assert(code.match(/firstLetterOfLastName\s*?=\s*?lastName\[.*?\]/)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-last-character-in-a-string.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-last-character-in-a-string.md index 6643d6d469..33d84f8e05 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-last-character-in-a-string.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-last-character-in-a-string.md @@ -1,6 +1,6 @@ --- id: bd7123c9c451eddfaeb5bdef -title: Use Bracket Notation to Find the Last Character in a String +title: 使用方括号查找字符串中的最后一个字符 challengeType: 1 videoUrl: 'https://scrimba.com/c/cBZQGcv' forumTopicId: 18342 @@ -9,32 +9,34 @@ dashedName: use-bracket-notation-to-find-the-last-character-in-a-string # --description-- -In order to get the last letter of a string, you can subtract one from the string's length. +要获取字符串的最后一个字符,可以用字符串的长度减 1 的索引值。 -For example, if `var firstName = "Charles"`, you can get the value of the last letter of the string by using `firstName[firstName.length - 1]`. +例如,在 `var firstName = "Charles"` 中,可以用 `firstName[firstName.length - 1]` 来得到字符串的最后的一个字符。 -Example: +示例: ```js var firstName = "Charles"; -var lastLetter = firstName[firstName.length - 1]; // lastLetter is "s" +var lastLetter = firstName[firstName.length - 1]; ``` +`lastLetter` 值为字符串 `s`。 + # --instructions-- -Use bracket notation to find the last character in the `lastName` variable. +使用方括号表示法( bracket notation)来找到 `lastName` 变量中的最后一个字符。 -**Hint:** Try looking at the example above if you get stuck. +**提示:** 如果卡住了,请尝试查看上面的示例。 # --hints-- -`lastLetterOfLastName` should be "e". +`lastLetterOfLastName` 应该是字母 `e`。 ```js assert(lastLetterOfLastName === 'e'); ``` -You should use `.length` to get the last letter. +您应该使用 `.length` 获取最后一个字母。 ```js assert(code.match(/\.length/g).length > 0); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-nth-character-in-a-string.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-nth-character-in-a-string.md index b3c183a904..d5e2158e63 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-nth-character-in-a-string.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-nth-character-in-a-string.md @@ -1,6 +1,6 @@ --- id: bd7123c9c450eddfaeb5bdef -title: Use Bracket Notation to Find the Nth Character in a String +title: 使用方括号查找字符串中的第 N 个字符 challengeType: 1 videoUrl: 'https://scrimba.com/c/cWPVJua' forumTopicId: 18343 @@ -9,32 +9,34 @@ dashedName: use-bracket-notation-to-find-the-nth-character-in-a-string # --description-- -You can also use bracket notation to get the character at other positions within a string. +你也可以使用方括号( bracket notation)来获得一个字符串中的其他位置的字符。 -Remember that computers start counting at `0`, so the first character is actually the zeroth character. +请记住,程序是从 `0` 开始计数,所以获取第一个字符实际上是第零个字符串。 -Example: +例如: ```js var firstName = "Ada"; -var secondLetterOfFirstName = firstName[1]; // secondLetterOfFirstName is "d" +var secondLetterOfFirstName = firstName[1]; ``` +`secondLetterOfFirstName` 值应该为字符串 `d`。 + # --instructions-- -Let's try to set `thirdLetterOfLastName` to equal the third letter of the `lastName` variable using bracket notation. +让我们使用方括号,把 `lastName` 变量的第三个字符赋值给 `thirdLetterOfLastName`。 -**Hint:** Try looking at the example above if you get stuck. +**提示:** 如果卡住了,请尝试查看上面的示例。 # --hints-- -The `thirdLetterOfLastName` variable should have the value of `v`. +`thirdLetterOfLastName` 变量值应该为 `v` 。 ```js assert(thirdLetterOfLastName === 'v'); ``` -You should use bracket notation. +应该使用方括号表示法。 ```js assert(code.match(/thirdLetterOfLastName\s*?=\s*?lastName\[.*?\]/)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-nth-to-last-character-in-a-string.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-nth-to-last-character-in-a-string.md index 0cb27719b0..5107af10e9 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-nth-to-last-character-in-a-string.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-nth-to-last-character-in-a-string.md @@ -1,6 +1,6 @@ --- id: bd7123c9c452eddfaeb5bdef -title: Use Bracket Notation to Find the Nth-to-Last Character in a String +title: 使用方括号查找字符串中的倒数第 N 个字符 challengeType: 1 videoUrl: 'https://scrimba.com/c/cw4vkh9' forumTopicId: 18344 @@ -9,32 +9,34 @@ dashedName: use-bracket-notation-to-find-the-nth-to-last-character-in-a-string # --description-- -You can use the same principle we just used to retrieve the last character in a string to retrieve the Nth-to-last character. +我们既可以获取字符串的最后一个字符,也可以用获取字符串的倒数第 N 个字符。 -For example, you can get the value of the third-to-last letter of the `var firstName = "Charles"` string by using `firstName[firstName.length - 3]` +例如,你可以这样 `firstName[firstName.length - 3]` 来获得 `var firstName = "Charles"` 字符串中的倒数第三个字符。 -Example: +例如: ```js var firstName = "Charles"; -var thirdToLastLetter = firstName[firstName.length - 3]; // thirdToLastLetter is "l" +var thirdToLastLetter = firstName[firstName.length - 3]; ``` +`thirdToLastLetter` 的值应该为字符串 `l`。 + # --instructions-- -Use bracket notation to find the second-to-last character in the `lastName` string. +使用方括号( bracket notation)来获得 `lastName` 字符串中的倒数第二个字符。 -**Hint:** Try looking at the example above if you get stuck. +**提示:** 如果卡住了,请尝试查看上面的示例。 # --hints-- -`secondToLastLetterOfLastName` should be "c". +`secondToLastLetterOfLastName` 应该是字母 `c`。 ```js assert(secondToLastLetterOfLastName === 'c'); ``` -You should use `.length` to get the second last letter. +您应该使用 `.length` 获取倒数第二个字母。 ```js assert(code.match(/\.length/g).length > 0); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-conditional-logic-with-if-statements.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-conditional-logic-with-if-statements.md index e90542e170..cfb4c53674 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-conditional-logic-with-if-statements.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-conditional-logic-with-if-statements.md @@ -1,6 +1,6 @@ --- id: cf1111c1c12feddfaeb3bdef -title: Use Conditional Logic with If Statements +title: 用 if 语句来表达条件逻辑 challengeType: 1 videoUrl: 'https://scrimba.com/c/cy87mf3' forumTopicId: 18348 @@ -9,15 +9,15 @@ dashedName: use-conditional-logic-with-if-statements # --description-- -`If` statements are used to make decisions in code. The keyword `if` tells JavaScript to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as `Boolean` conditions and they may only be `true` or `false`. +`If` 语句用于在代码中做条件判断。 关键字 `if` 告诉 JavaScript 在小括号中的条件为真的情况下去执行定义在大括号里面的代码。 这种条件被称为 `Boolean` 条件,因为他们只可能是 `true`(真)或 `false`(假)。 -When the condition evaluates to `true`, the program executes the statement inside the curly braces. When the Boolean condition evaluates to `false`, the statement inside the curly braces will not execute. +当条件的计算结果为 `true`,程序执行大括号内的语句。 当布尔条件的计算结果为 `false`,大括号内的代码将不会执行。 -**Pseudocode** +**伪代码** -
if (condition is true) {
  statement is executed
}
+
if(条件为真){
语句被执行
}
-**Example** +**示例** ```js function test (myCondition) { @@ -26,43 +26,45 @@ function test (myCondition) { } return "It was false"; } -test(true); // returns "It was true" -test(false); // returns "It was false" +test(true); +test(false); ``` -When `test` is called with a value of `true`, the `if` statement evaluates `myCondition` to see if it is `true` or not. Since it is `true`, the function returns `"It was true"`. When we call `test` with a value of `false`, `myCondition` is *not* `true` and the statement in the curly braces is not executed and the function returns `"It was false"`. +`test(true)` 返回字符串 `It was true`,`test(false)` 返回字符串 `It was false`。 + +当 `test` 被调用,并且传递进来的参数值为 `true` 时,`if` 语句会计算 `myCondition` 的结果,看它是否为 `true`。 如果条件为 `true`,函数会返回 `It was true`。 当 `test` 被调用,并且传递进来的参数值为 `false` 时,`myCondition` *不* 为 `true`,并且不执行大括号后面的语句,函数返回 `It was false`。 # --instructions-- -Create an `if` statement inside the function to return `"Yes, that was true"` if the parameter `wasThatTrue` is `true` and return `"No, that was false"` otherwise. +在函数内部创建一个 `if` 语句,如果该参数 `wasThatTrue` 值为 `true`,返回 `Yes, that was true`,否则,返回`No, that was false`。 # --hints-- -`trueOrFalse` should be a function +`trueOrFalse` 应该是一个函数 ```js assert(typeof trueOrFalse === 'function'); ``` -`trueOrFalse(true)` should return a string +`trueOrFalse(true)` 应该返回一个字符串 ```js assert(typeof trueOrFalse(true) === 'string'); ``` -`trueOrFalse(false)` should return a string +`trueOrFalse(false)` 应该返回一个字符串 ```js assert(typeof trueOrFalse(false) === 'string'); ``` -`trueOrFalse(true)` should return "Yes, that was true" +`trueOrFalse(true)` 应该返回 `Yes, that was true` ```js assert(trueOrFalse(true) === 'Yes, that was true'); ``` -`trueOrFalse(false)` should return "No, that was false" +`trueOrFalse(false)`应该返回 `No, that was false` ```js assert(trueOrFalse(false) === 'No, that was false'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-multiple-conditional-ternary-operators.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-multiple-conditional-ternary-operators.md index 73a2120e7f..32351ccac5 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-multiple-conditional-ternary-operators.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-multiple-conditional-ternary-operators.md @@ -1,6 +1,6 @@ --- id: 587d7b7e367417b2b2512b21 -title: Use Multiple Conditional (Ternary) Operators +title: 使用多个三元运算符 challengeType: 1 videoUrl: 'https://scrimba.com/c/cyWJBT4' forumTopicId: 301179 @@ -9,9 +9,9 @@ dashedName: use-multiple-conditional-ternary-operators # --description-- -In the previous challenge, you used a single conditional operator. You can also chain them together to check for multiple conditions. +在之前的挑战中,你使用了一个条件运算符。 你也可以将多个运算符串联在一起以检查多种条件。 -The following function uses if, else if, and else statements to check multiple conditions: +下面的函数使用 `if`,`else if` 和 `else` 语句来检查多个条件: ```js function findGreaterOrEqual(a, b) { @@ -27,7 +27,7 @@ function findGreaterOrEqual(a, b) { } ``` -The above function can be re-written using multiple conditional operators: +以上函数可以使用多个三元运算符重写: ```js function findGreaterOrEqual(a, b) { @@ -37,7 +37,7 @@ function findGreaterOrEqual(a, b) { } ``` -It is considered best practice to format multiple conditional operators such that each condition is on a separate line, as shown above. Using multiple conditional operators without proper indentation may make your code hard to read. For example: +如上文所示,对多个三元运算符进行每个条件都是单独一行的格式化被认为是最佳做法。 使用多个三元运算符而没有适当的缩进可能会使您的代码难以理解。 例如: ```js function findGreaterOrEqual(a, b) { @@ -47,29 +47,29 @@ function findGreaterOrEqual(a, b) { # --instructions-- -In the `checkSign` function, use multiple conditional operators - following the recommended format used in `findGreaterOrEqual` - to check if a number is positive, negative or zero. The function should return `"positive"`, `"negative"` or `"zero"`. +在 `checkSign` 函数中使用多个三元运算符来检查数字是正数 ("positive")、负数 ("negative") 或零 ("zero"),使用 `findGreaterOrEqual` 里面的建议缩进格式。 函数应返回 `positive`、`negative` 或 `zero`。 # --hints-- -`checkSign` should use multiple conditional operators +`checkSign` 应该使用多个三元运算符。 ```js assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?\s*?\?\s*?.+?\s*?:\s*?.+?/gi.test(code)); ``` -`checkSign(10)` should return "positive". Note that capitalization matters +`checkSign(10)` 应该返回字符串 `positive`。 注意区分大写字母和小写字母。 ```js assert(checkSign(10) === 'positive'); ``` -`checkSign(-12)` should return "negative". Note that capitalization matters +`checkSign(-12)` 应该返回字符串 `negative`。 注意区分大写字母和小写字母。 ```js assert(checkSign(-12) === 'negative'); ``` -`checkSign(0)` should return "zero". Note that capitalization matters +`checkSign(0)` 应该返回字符串 `zero`. 注意区分大写字母和小写字母。 ```js assert(checkSign(0) === 'zero'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-countdown.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-countdown.md index 44eace9821..bcd774cd2d 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-countdown.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-countdown.md @@ -1,6 +1,6 @@ --- id: 5cd9a70215d3c4e65518328f -title: Use Recursion to Create a Countdown +title: 使用递归创建一个倒计时 challengeType: 1 forumTopicId: 305925 dashedName: use-recursion-to-create-a-countdown @@ -8,11 +8,11 @@ dashedName: use-recursion-to-create-a-countdown # --description-- -In a [previous challenge](/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion), you learned how to use recursion to replace a for loop. Now, let's look at a more complex function that returns an array of consecutive integers starting with `1` through the number passed to the function. +在上一个[挑战](/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion),学习了怎样用递归来代替 `for` 循环。 现在来学习一个更复杂的函数,函数返回一个从 `1` 到传递给函数的指定数字的连续数字数组。 -As mentioned in the previous challenge, there will be a base case. The base case tells the recursive function when it no longer needs to call itself. It is a simple case where the return value is already known. There will also be a recursive call which executes the original function with different arguments. If the function is written correctly, eventually the base case will be reached. +正如上一个挑战提到的,会有一个 base case。 base case 告诉递归函数什么时候不在需要调用其自身。 这是简单 情况,返回得到的值。 还有 recursive call,继续用不同的参数调用自身。 如果函数无误,一直执行直到 base case 为止。 -For example, say you want to write a recursive function that returns an array containing the numbers `1` through `n`. This function will need to accept an argument, `n`, representing the final number. Then it will need to call itself with progressively smaller values of `n` until it reaches `1`. You could write the function as follows: +比如,如果想写一个递归函数,返回一个数字 `1` 到 `n` 的连续数组。 这个函数需要接收一个参数 `n` 代表最终数字。 然后会持续的调用自身,传入一个比 `n` 更小的值一直到传入的值是 `1` 为止。 函数如下: ```javascript function countup(n) { @@ -24,36 +24,38 @@ function countup(n) { return countArray; } } -console.log(countup(5)); // [ 1, 2, 3, 4, 5 ] +console.log(countup(5)); ``` -At first, this seems counterintuitive since the value of `n` *decreases*, but the values in the final array are *increasing*. This happens because the push happens last, after the recursive call has returned. At the point where `n` is pushed into the array, `countup(n - 1)` has already been evaluated and returned `[1, 2, ..., n - 1]`. +值 `[1, 2, 3, 4, 5]` 将显示在控制台中。 + +起初,这似乎是违反直觉的,因为 `n` 的值*递减*,但是最终数组中的值却*递增*。 之所以发生这种情况,是因为在递归调用返回之后,才调用 push。 在将 `n` pushed 进数组时,`countup(n - 1)` 已经调用赋值成功并返回了 `[1, 2, ..., n - 1]`。 # --instructions-- -We have defined a function called `countdown` with one parameter (`n`). The function should use recursion to return an array containing the integers `n` through `1` based on the `n` parameter. If the function is called with a number less than 1, the function should return an empty array. For example, calling this function with `n = 5` should return the array `[5, 4, 3, 2, 1]`. Your function must use recursion by calling itself and must not use loops of any kind. +已经定义了一个函数 `countdown`,函数有一个参数(`n`)。 函数应该基于参数 `n` 递归调用返回 `n` 到 `1` 的连续数字的数组。 如果函数以小于 1 的参数调用,函数应该返回空数组。 比如,用 `n = 5` 调用函数应该返回数组 `[5, 4, 3, 2, 1]`。 函数必需使用递归函数调用自身,不能使用任何形式的循环。 # --hints-- -`countdown(-1)` should return an empty array. +`countdown(-1)` 应该返回一个空数组。 ```js assert.isEmpty(countdown(-1)); ``` -`countdown(10)` should return `[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]` +`countdown(10)` 应该返回 `[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]`。 ```js assert.deepStrictEqual(countdown(10), [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]); ``` -`countdown(5)` should return `[5, 4, 3, 2, 1]` +`countdown(5)` 应该返回 `[5, 4, 3, 2, 1]`。 ```js assert.deepStrictEqual(countdown(5), [5, 4, 3, 2, 1]); ``` -Your code should not rely on any kind of loops (`for`, `while` or higher order functions such as `forEach`, `map`, `filter`, and `reduce`). +代码不能包含任意形式的循环(`for`、`while` 或者高阶函数如:`forEach`、`map`、`filter` 以及 `reduce`)。 ```js assert( @@ -63,7 +65,7 @@ assert( ); ``` -You should use recursion to solve this problem. +应该用递归解决这个问题。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-range-of-numbers.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-range-of-numbers.md index 2e10a18bfb..438d745a96 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-range-of-numbers.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-range-of-numbers.md @@ -1,6 +1,6 @@ --- id: 5cc0bd7a49b71cb96132e54c -title: Use Recursion to Create a Range of Numbers +title: 使用递归来创建一个数字序列 challengeType: 1 forumTopicId: 301180 dashedName: use-recursion-to-create-a-range-of-numbers @@ -8,21 +8,21 @@ dashedName: use-recursion-to-create-a-range-of-numbers # --description-- -Continuing from the previous challenge, we provide you another opportunity to create a recursive function to solve a problem. +接着上一个挑战,有另外一个机会来用递归函数解决问题。 # --instructions-- -We have defined a function named `rangeOfNumbers` with two parameters. The function should return an array of integers which begins with a number represented by the `startNum` parameter and ends with a number represented by the `endNum` parameter. The starting number will always be less than or equal to the ending number. Your function must use recursion by calling itself and not use loops of any kind. It should also work for cases where both `startNum` and `endNum` are the same. +已经定义好了 `rangeOfNumbers` 函数,包含两个参数。 函数应该返回一个连续数字数组,`startNum` 参数开始 `endNum` 参数截止。 开始的数字小于或等于截止数字。 函数必需递归调用自身,不能使用任意形式的循环。 要考虑到 `startNum` 和 `endNum` 相同的情况。 # --hints-- -Your function should return an array. +函数应该返回一个数组。 ```js assert(Array.isArray(rangeOfNumbers(5, 10))); ``` -Your code should not use any loop syntax (`for` or `while` or higher order functions such as `forEach`, `map`, `filter`, or `reduce`). +不能包含循环语句(`for` 或者 `while` 或者高阶函数比如 `forEach`、`map`、`filter` 或者 `reduce`)。 ```js assert( @@ -32,7 +32,7 @@ assert( ); ``` -`rangeOfNumbers` should use recursion (call itself) to solve this challenge. +`rangeOfNumbers` 应该使用递归函数(调用自身)来完成这个挑战。 ```js assert( @@ -42,19 +42,19 @@ assert( ); ``` -`rangeOfNumbers(1, 5)` should return `[1, 2, 3, 4, 5]`. +`rangeOfNumbers(1, 5)` 应该返回 `[1, 2, 3, 4, 5]`。 ```js assert.deepStrictEqual(rangeOfNumbers(1, 5), [1, 2, 3, 4, 5]); ``` -`rangeOfNumbers(6, 9)` should return `[6, 7, 8, 9]`. +`rangeOfNumbers(6, 9)` 应该返回 `[6, 7, 8, 9]`。 ```js assert.deepStrictEqual(rangeOfNumbers(6, 9), [6, 7, 8, 9]); ``` -`rangeOfNumbers(4, 4)` should return `[4]`. +`rangeOfNumbers(4, 4)` 应该返回 `[4]`。 ```js assert.deepStrictEqual(rangeOfNumbers(4, 4), [4]); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-conditional-ternary-operator.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-conditional-ternary-operator.md index 0a8808b0a8..eedbb0fc48 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-conditional-ternary-operator.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-conditional-ternary-operator.md @@ -1,6 +1,6 @@ --- id: 587d7b7e367417b2b2512b24 -title: Use the Conditional (Ternary) Operator +title: 使用三元运算符 challengeType: 1 forumTopicId: 301181 dashedName: use-the-conditional-ternary-operator @@ -8,13 +8,11 @@ dashedName: use-the-conditional-ternary-operator # --description-- -The conditional operator, also called the ternary operator, can be used as a one line if-else expression. +条件运算符( conditional operator,)(也称为三元运算符( ternary operator))的就像写成一行的 if-else 表达式 -The syntax is: +语法是 `a ? b: c`,其中 `a` 是条件,`b` 是条件返回 `true` 时要运行的代码,`c` 是条件返回 `false` 时要运行的代码。 -`condition ? expression-if-true : expression-if-false;` - -The following function uses an if-else statement to check a condition: +以下函数使用 `if/else` 语句来检查条件: ```js function findGreater(a, b) { @@ -27,7 +25,7 @@ function findGreater(a, b) { } ``` -This can be re-written using the `conditional operator`: +这可以使用三元运算符重写: ```js function findGreater(a, b) { @@ -37,29 +35,29 @@ function findGreater(a, b) { # --instructions-- -Use the `conditional operator` in the `checkEqual` function to check if two numbers are equal or not. The function should return either "Equal" or "Not Equal". +在 `checkEqual` 函数中使用三元运算符检查两个数字是否相等。 函数应该返回 `Equal` 或字符串 `Not Equal`。 # --hints-- -`checkEqual` should use the `conditional operator` +`checkEqual` 应该使用条件运算符。 ```js assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?/.test(code)); ``` -`checkEqual(1, 2)` should return "Not Equal" +`checkEqual(1, 2)` 应该返回字符串 `Not Equal` ```js assert(checkEqual(1, 2) === 'Not Equal'); ``` -`checkEqual(1, 1)` should return "Equal" +`checkEqual(1, 1)` 应该返回字符串 `Equal` ```js assert(checkEqual(1, 1) === 'Equal'); ``` -`checkEqual(1, -1)` should return "Not Equal" +`checkEqual(1, -1)` 应该返回字符串 `Not Equal` ```js assert(checkEqual(1, -1) === 'Not Equal'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-parseint-function-with-a-radix.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-parseint-function-with-a-radix.md index 7d83a60eb9..b6df219cb2 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-parseint-function-with-a-radix.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-parseint-function-with-a-radix.md @@ -1,6 +1,6 @@ --- id: 587d7b7e367417b2b2512b22 -title: Use the parseInt Function with a Radix +title: 使用 parseInt 函数并传入一个基数 challengeType: 1 videoUrl: 'https://scrimba.com/c/c6K4Kh3' forumTopicId: 301182 @@ -9,49 +9,49 @@ dashedName: use-the-parseint-function-with-a-radix # --description-- -The `parseInt()` function parses a string and returns an integer. It takes a second argument for the radix, which specifies the base of the number in the string. The radix can be an integer between 2 and 36. +`parseInt()` 函数解析一个字符串并返回一个整数。 它还可以传入第二个参数,指定了字符串中数字的基数。 基数可以是 2 到 36 之间的整数。 -The function call looks like: +函数调用如下所示: `parseInt(string, radix);` -And here's an example: +示例: `var a = parseInt("11", 2);` -The radix variable says that "11" is in the binary system, or base 2. This example converts the string "11" to an integer 3. +参数 2 表示 `11` 使用二进制数。 此示例将字符串 `11` 转换为整数 `3`。 # --instructions-- -Use `parseInt()` in the `convertToInteger` function so it converts a binary number to an integer and returns it. +在 `convertToInteger` 函数中使用 `parseInt()` 将二进制数转换为正数并返回。 # --hints-- -`convertToInteger` should use the `parseInt()` function +`convertToInteger` 中应该使用 `parseInt()` 函数 ```js assert(/parseInt/g.test(code)); ``` -`convertToInteger("10011")` should return a number +`convertToInteger("10011")` 应该返回一个数字 ```js assert(typeof convertToInteger('10011') === 'number'); ``` -`convertToInteger("10011")` should return 19 +`convertToInteger("10011")` 应该返回 19 ```js assert(convertToInteger('10011') === 19); ``` -`convertToInteger("111001")` should return 57 +`convertToInteger("111001")` 应该返回 57 ```js assert(convertToInteger('111001') === 57); ``` -`convertToInteger("JamesBond")` should return NaN +`convertToInteger("JamesBond")` 应该返回 `NaN` ```js assert.isNaN(convertToInteger('JamesBond')); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-parseint-function.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-parseint-function.md index 94d85f0bdd..f1382c051e 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-parseint-function.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-parseint-function.md @@ -1,6 +1,6 @@ --- id: 587d7b7e367417b2b2512b23 -title: Use the parseInt Function +title: 使用 parseInt 函数 challengeType: 1 videoUrl: 'https://scrimba.com/c/cm83LSW' forumTopicId: 301183 @@ -9,43 +9,43 @@ dashedName: use-the-parseint-function # --description-- -The `parseInt()` function parses a string and returns an integer. Here's an example: +`parseInt()` 函数解析一个字符串返回一个整数。 下面是一个示例: `var a = parseInt("007");` -The above function converts the string "007" to an integer 7. If the first character in the string can't be converted into a number, then it returns `NaN`. +上述函数将字符串 `007` 转换为整数 `7`。 如果字符串参数的第一个字符是字符串类型的,结果将不会转换成数字,而是返回 `NaN`。 # --instructions-- -Use `parseInt()` in the `convertToInteger` function so it converts the input string `str` into an integer, and returns it. +在 `convertToInteger` 函数中使用 `parseInt()` 将字符串 `str` 转换为正数并返回。 # --hints-- -`convertToInteger` should use the `parseInt()` function +`convertToInteger` 应该使用 `parseInt()` 函数 ```js assert(/parseInt/g.test(code)); ``` -`convertToInteger("56")` should return a number +`convertToInteger("56")` 应该返回一个数字 ```js assert(typeof convertToInteger('56') === 'number'); ``` -`convertToInteger("56")` should return 56 +`convertToInteger("56")` 应该返回 56 ```js assert(convertToInteger('56') === 56); ``` -`convertToInteger("77")` should return 77 +`convertToInteger("77")`应该返回 77 ```js assert(convertToInteger('77') === 77); ``` -`convertToInteger("JamesBond")` should return NaN +`convertToInteger("JamesBond")`应该返回 `NaN` ```js assert.isNaN(convertToInteger('JamesBond')); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/using-objects-for-lookups.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/using-objects-for-lookups.md index 1185e31c24..16dc56565c 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/using-objects-for-lookups.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/using-objects-for-lookups.md @@ -1,6 +1,6 @@ --- id: 56533eb9ac21ba0edf2244ca -title: Using Objects for Lookups +title: 使用对象进行查找 challengeType: 1 videoUrl: 'https://scrimba.com/c/cdBk8sM' forumTopicId: 18373 @@ -9,9 +9,9 @@ dashedName: using-objects-for-lookups # --description-- -Objects can be thought of as a key/value storage, like a dictionary. If you have tabular data, you can use an object to "lookup" values rather than a `switch` statement or an `if/else` chain. This is most useful when you know that your input data is limited to a certain range. +对象和字典一样,可以用来存储键/值对。 如果数据是扁平的,你可以用对象来查找你想要的值,而不是链式使用 `switch` 或 `if/else` 语句。 当你知道你的输入数据在某个范围时,这种查找方式极为有效。 -Here is an example of a simple reverse alphabet lookup: +这是简单的反向字母表: ```js var alpha = { @@ -24,68 +24,70 @@ var alpha = { 25:"B", 26:"A" }; -alpha[2]; // "Y" -alpha[24]; // "C" +alpha[2]; +alpha[24]; var value = 2; -alpha[value]; // "Y" +alpha[value]; ``` +`alpha[2]` 是字符串 `Y`,`alpha[24]` 是字符串 `C`,`alpha[value]` 是字符串 `Y`。 + # --instructions-- -Convert the switch statement into an object called `lookup`. Use it to look up `val` and assign the associated string to the `result` variable. +把 switch 语句转化为对象 `lookup` 调用。 使用它来查找 `val` 属性的值,并赋值给 `result` 变量。 # --hints-- -`phoneticLookup("alpha")` should equal `"Adams"` +`phoneticLookup("alpha")` 应该等于 `Adams` ```js assert(phoneticLookup('alpha') === 'Adams'); ``` -`phoneticLookup("bravo")` should equal `"Boston"` +`phoneticLookup("bravo")` 应该等于 `Boston` ```js assert(phoneticLookup('bravo') === 'Boston'); ``` -`phoneticLookup("charlie")` should equal `"Chicago"` +`phoneticLookup("charlie")` 应该等于 `Chicago` ```js assert(phoneticLookup('charlie') === 'Chicago'); ``` -`phoneticLookup("delta")` should equal `"Denver"` +`phoneticLookup("delta")` 应该等于 `Denver` ```js assert(phoneticLookup('delta') === 'Denver'); ``` -`phoneticLookup("echo")` should equal `"Easy"` +`phoneticLookup("echo")` 应该等于 `Easy` ```js assert(phoneticLookup('echo') === 'Easy'); ``` -`phoneticLookup("foxtrot")` should equal `"Frank"` +`phoneticLookup("foxtrot")` 应该等于字符串 `Frank` ```js assert(phoneticLookup('foxtrot') === 'Frank'); ``` -`phoneticLookup("")` should equal `undefined` +`phoneticLookup("")` 应该等于 `undefined`。 ```js assert(typeof phoneticLookup('') === 'undefined'); ``` -You should not modify the `return` statement +请不要修改 `return` 语句 ```js assert(code.match(/return\sresult;/)); ``` -You should not use `case`, `switch`, or `if` statements +请不要使用 `case`、`switch`、`if` 语句 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/word-blanks.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/word-blanks.md index 37ab2df30c..9551e57fda 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/word-blanks.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/word-blanks.md @@ -1,6 +1,6 @@ --- id: 56533eb9ac21ba0edf2244bb -title: Word Blanks +title: 填词造句 challengeType: 1 videoUrl: 'https://scrimba.com/c/caqn8zuP' forumTopicId: 18377 @@ -9,11 +9,11 @@ dashedName: word-blanks # --description-- -We will now use our knowledge of strings to build a "[Mad Libs](https://en.wikipedia.org/wiki/Mad_Libs)" style word game we're calling "Word Blanks". You will create an (optionally humorous) "Fill in the Blanks" style sentence. +现在,我们来用字符串的相关知识实现一个 "[Mad Libs](https://en.wikipedia.org/wiki/Mad_Libs)" 类的文字游戏,称为 "Word Blanks"。 你将创建一个(可选幽默的)“填空”样式句子。 -In a "Mad Libs" game, you are provided sentences with some missing words, like nouns, verbs, adjectives and adverbs. You then fill in the missing pieces with words of your choice in a way that the completed sentence makes sense. +在 "Mad Libs" 游戏中,提供一个缺少一些单词的句子,缺少的单词包括名词、动词、形容词和副词等。 然后,你选择一些单词填写句子缺失的地方,使句子完整并且有意义。 -Consider this sentence - "It was really **\_\_\_\_**, and we **\_\_\_\_** ourselves **\_\_\_\_**". This sentence has three missing pieces- an adjective, a verb and an adverb, and we can add words of our choice to complete it. We can then assign the completed sentence to a variable as follows: +思考一下这句话 - It was really **\_\_\_\_**, and we **\_\_\_\_** ourselves **\_\_\_\_**。 这句话有三个缺失的部分 - 形容词、动词和副词,选择合适单词填入完成它。 然后将完成的句子赋值给变量,如下所示: ```js var sentence = "It was really " + "hot" + ", and we " + "laughed" + " ourselves " + "silly" + "."; @@ -21,21 +21,21 @@ var sentence = "It was really " + "hot" + ", and we " + "laughed" + " ourselves # --instructions-- -In this challenge, we provide you with a noun, a verb, an adjective and an adverb. You need to form a complete sentence using words of your choice, along with the words we provide. +在这个挑战中,我们为你提供名词、动词、形容词和副词。 你需要使用合适单词以及我们提供的单词来形成完整的句子。 -You will need to use the string concatenation operator `+` to build a new string, using the provided variables: `myNoun`, `myAdjective`, `myVerb`, and `myAdverb`. You will then assign the formed string to the `wordBlanks` variable. You should not change the words assigned to the variables. +你需要使用字符串连接运算符 `+` 来拼接字符串变量:`myNoun`、`myAdjective`、`myVerb` 和 `myAdverb` 来构建一个新字符串。 然后,将新字符串赋给 `wordBlanks` 变量。 您不应该更改分配给变量的单词。 -You will also need to account for spaces in your string, so that the final sentence has spaces between all the words. The result should be a complete sentence. +你还需要考虑字符串中的空格,确保句子的所有单词之间有空格。 结果应该是一个完整的句子。 # --hints-- -`wordBlanks` should be a string. +`wordBlanks` 应该返回一个字符串。 ```js assert(typeof wordBlanks === 'string'); ``` -You should not change the values assigned to `myNoun`, `myVerb`, `myAdjective` or `myAdverb`. +不能改变 `myNoun`、`myVerb`、`myAdjective` 或者 `myAdverb` 的值。 ```js assert( @@ -46,7 +46,7 @@ assert( ); ``` -You should not directly use the values "dog", "ran", "big", or "quickly" to create `wordBlanks`. +您不应该直接使用 `dog`、`ran`、`big` 或 `quickly` 来创建 `wordBlanks`。 ```js const newCode = removeAssignments(code); @@ -58,7 +58,7 @@ assert( ); ``` -`wordBlanks` should contain all of the words assigned to the variables `myNoun`, `myVerb`, `myAdjective` and `myAdverb` separated by non-word characters (and any additional words in your madlib). +`wordBlanks` 应包含赋值给变量 `myNoun`、`myVerb`、`myAdjective` 和 `myAdverb` 的所有单词,并用非单词字符(以及 madlib 中的其它单词)分隔。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/write-reusable-javascript-with-functions.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/write-reusable-javascript-with-functions.md index 2fb3ca9cd8..f084211d8c 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/write-reusable-javascript-with-functions.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/write-reusable-javascript-with-functions.md @@ -1,6 +1,6 @@ --- id: 56bbb991ad1ed5201cd392cf -title: Write Reusable JavaScript with Functions +title: 用函数编写可重用代码 challengeType: 1 videoUrl: 'https://scrimba.com/c/cL6dqfy' forumTopicId: 18378 @@ -9,9 +9,9 @@ dashedName: write-reusable-javascript-with-functions # --description-- -In JavaScript, we can divide up our code into reusable parts called functions. +在 JavaScript 中,我们可以把代码的重复部分抽取出来,放到一个函数 (functions)中。 -Here's an example of a function: +举个例子: ```js function functionName() { @@ -19,27 +19,27 @@ function functionName() { } ``` -You can call or invoke this function by using its name followed by parentheses, like this: `functionName();` Each time the function is called it will print out the message `"Hello World"` on the dev console. All of the code between the curly braces will be executed every time the function is called. +你可以通过函数名加上后面的小括号来调用(invoke)这个函数,就像这样: `functionName();` 每次调用函数时,它都会在控制台上打印消息 `Hello World`。 每次调用函数时,大括号之间的所有代码都将被执行。 # --instructions-- -
  1. Create a function called reusableFunction which prints "Hi World" to the dev console.
  2. Call the function.
+
  1. 先创建一个名为 reusableFunction 的函数,这个函数可以打印 "Hi World" 到控制台上。
  2. 然后调用这个函数。
# --hints-- -`reusableFunction` should be a function. +`reusableFunction` 应该是一个函数。 ```js assert(typeof reusableFunction === 'function'); ``` -`reusableFunction` should output "Hi World" to the dev console. +`reusableFunction` 应该将字符串 `Hi World` 输出到控制台。 ```js assert(hiWorldWasLogged); ``` -You should call `reusableFunction` after you define it. +在你定义 `reusableFunction` 之后记得调用它。 ```js assert(/^\s*reusableFunction\(\)\s*/m.test(code)); @@ -87,7 +87,9 @@ if (typeof reusableFunction !== "function") { ``` ## --seed-contents-- + ```js + ``` # --solutions-- diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-missing-open-and-closing-parenthesis-after-a-function-call.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-missing-open-and-closing-parenthesis-after-a-function-call.md index 5a4e0fc060..4364de3b8b 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-missing-open-and-closing-parenthesis-after-a-function-call.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-missing-open-and-closing-parenthesis-after-a-function-call.md @@ -1,6 +1,6 @@ --- id: 587d7b85367417b2b2512b39 -title: Catch Missing Open and Closing Parenthesis After a Function Call +title: 捕捉函数调用后缺少的左括号和右括号 challengeType: 1 forumTopicId: 301185 dashedName: catch-missing-open-and-closing-parenthesis-after-a-function-call @@ -8,31 +8,33 @@ dashedName: catch-missing-open-and-closing-parenthesis-after-a-function-call # --description-- -When a function or method doesn't take any arguments, you may forget to include the (empty) opening and closing parentheses when calling it. Often times the result of a function call is saved in a variable for other use in your code. This error can be detected by logging variable values (or their types) to the console and seeing that one is set to a function reference, instead of the expected value the function returns. +当函数或方法不接受任何参数时,你可能忘记在调用它时加上空的左括号和右括号。 通常,函数调用的结果会保存在变量中,供其他代码使用。 可以通过将变量值(或其类型)打印到控制台,查看输出究竟是一个函数引用还是函数调用的返回值来检测这类错误。 -The variables in the following example are different: +下面示例中的两个变量是不同的: ```js function myFunction() { return "You rock!"; } -let varOne = myFunction; // set to equal a function -let varTwo = myFunction(); // set to equal the string "You rock!" +let varOne = myFunction; +let varTwo = myFunction(); ``` +这里 `varOne` 是函数 `myFunction` ,`varTwo` 是字符串 `You rock!` + # --instructions-- -Fix the code so the variable `result` is set to the value returned from calling the function `getNine`. +修复代码,将变量 `result` 设置为调用函数 `getNine` 返回的值。 # --hints-- -Your code should fix the variable `result` so it is set to the number that the function `getNine` returns. +你应该修复变量 `result` 使其为函数 `getNine` 的返回的 number 值。 ```js assert(result == 9); ``` -Your code should call the `getNine` function. +你应该调用 `getNine` 函数。 ```js assert(code.match(/getNine\(\)/g).length == 2); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-mixed-usage-of-single-and-double-quotes.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-mixed-usage-of-single-and-double-quotes.md index cde18db798..da8f3954c9 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-mixed-usage-of-single-and-double-quotes.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-mixed-usage-of-single-and-double-quotes.md @@ -1,6 +1,6 @@ --- id: 587d7b84367417b2b2512b37 -title: Catch Mixed Usage of Single and Double Quotes +title: 捕捉单引号和双引号的混合用法 challengeType: 1 forumTopicId: 301188 dashedName: catch-mixed-usage-of-single-and-double-quotes @@ -8,40 +8,39 @@ dashedName: catch-mixed-usage-of-single-and-double-quotes # --description-- -JavaScript allows the use of both single (`'`) and double (`"`) quotes to declare a string. Deciding which one to use generally comes down to personal preference, with some exceptions. +JavaScript 允许使用单引号 (`'`) 和双引号 (`"`) 声明字符串。 决定使用哪一个通常看个人偏好,但有一些例外。 -Having two choices is great when a string has contractions or another piece of text that's in quotes. Just be careful that you don't close the string too early, which causes a syntax error. +如果字符串中有缩写或存在一段带引号的文本,你就会明白为什么 JavaScript 允许两种引号了。 请注意,不要提前用引号结束字符串,这会导致语法错误。 -Here are some examples of mixing quotes: +下面是混合使用引号的一些示例: ```js -// These are correct: const grouchoContraction = "I've had a perfectly wonderful evening, but this wasn't it."; const quoteInString = "Groucho Marx once said 'Quote me as saying I was mis-quoted.'"; -// This is incorrect: const uhOhGroucho = 'I've had a perfectly wonderful evening, but this wasn't it.'; ``` -Of course, it is okay to use only one style of quotes. You can escape the quotes inside the string by using the backslash (\\) escape character: +前两项是正确的,但第三项是不正确的。 + +当然,只使用一种引号也是可以的。 你可以使用反斜杠(`\`)转义字符来转义字符串中的引号: ```js -// Correct use of same quotes: const allSameQuotes = 'I\'ve had a perfectly wonderful evening, but this wasn\'t it.'; ``` # --instructions-- -Fix the string so it either uses different quotes for the `href` value, or escape the existing ones. Keep the double quote marks around the entire string. +修复字符串,使其对 `href` 值使用不同的引号,或者转义现有的引号。 在整个字符串周围保留双引号。 # --hints-- -Your code should fix the quotes around the `href` value "#Home" by either changing or escaping them. +你应通过更改或转义来修复 `href` 的值 `#Home` 周围的引号。 ```js assert(code.match(//g)); ``` -Your code should keep the double quotes around the entire string. +你应该在整个字符串外围保留双引号。 ```js assert(code.match(/"

.*?<\/p>";/g)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-off-by-one-errors-when-using-indexing.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-off-by-one-errors-when-using-indexing.md index d86487c484..dcc3414cb3 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-off-by-one-errors-when-using-indexing.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-off-by-one-errors-when-using-indexing.md @@ -1,6 +1,6 @@ --- id: 587d7b86367417b2b2512b3b -title: Catch Off By One Errors When Using Indexing +title: 捕获使用索引的时候出现的错误 challengeType: 1 forumTopicId: 301189 dashedName: catch-off-by-one-errors-when-using-indexing @@ -8,52 +8,51 @@ dashedName: catch-off-by-one-errors-when-using-indexing # --description-- -Off by one errors (sometimes called OBOE) crop up when you're trying to target a specific index of a string or array (to slice or access a segment), or when looping over the indices of them. JavaScript indexing starts at zero, not one, which means the last index is always one less than the length of the item. If you try to access an index equal to the length, the program may throw an "index out of range" reference error or print `undefined`. +当试图访问字符串或数组的特定索引(分割或访问一个片段)或循环索引时,有时会出现 Off by one errors 错误(有时称为 OBOE)。 JavaScript 索引从 0 开始,而不是 1,这意味着最后一个索引总会比字符串或数组的长度少 1。 如果尝试访问等于长度的索引,程序可能会抛出“索引超出范围”引用错误或打印出 `undefined`。 -When you use string or array methods that take index ranges as arguments, it helps to read the documentation and understand if they are inclusive (the item at the given index is part of what's returned) or not. Here are some examples of off by one errors: +当使用将索引范围作为参数的字符串或数组方法时,阅读相关的文档并了解参数中的索引的包含性(即是否考虑进返回值中)很重要。 以下是一些错误的示例: ```js let alphabet = "abcdefghijklmnopqrstuvwxyz"; let len = alphabet.length; for (let i = 0; i <= len; i++) { - // loops one too many times at the end console.log(alphabet[i]); } for (let j = 1; j < len; j++) { - // loops one too few times and misses the first character at index 0 console.log(alphabet[j]); } for (let k = 0; k < len; k++) { - // Goldilocks approves - this is just right console.log(alphabet[k]); } ``` +第一个例子多了一次循环,第二个例子少了一次循环(漏掉了索引 0 处的字符), 第三个例子是正确的。 + # --instructions-- -Fix the two indexing errors in the following function so all the numbers 1 through 5 are printed to the console. +修复以下函数中的两个索引错误,将 1 到 5 之间(包含 1 和 5)的所有数字打印到控制台。 # --hints-- -Your code should set the initial condition of the loop so it starts at the first index. +应该设置循环的初始条件,使循环从第一个索引开始。 ```js assert(code.match(/i\s*?=\s*?0\s*?;/g).length == 1); ``` -Your code should fix the initial condition of the loop so that the index starts at 0. +应修复循环的初始条件,使循环从索引 0 开始。 ```js assert(!code.match(/i\s?=\s*?1\s*?;/g)); ``` -Your code should set the terminal condition of the loop so it stops at the last index. +应该设置循环的终止条件,使循环在最后一个索引处停止。 ```js assert(code.match(/i\s*?<\s*?len\s*?;/g).length == 1); ``` -Your code should fix the terminal condition of the loop so that it stops at 1 before the length. +应该修复循环的终止条件,使循环在索引为字符串长度减 1 的位置停止。 ```js assert(!code.match(/i\s*?<=\s*?len;/g)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-unclosed-parentheses-brackets-braces-and-quotes.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-unclosed-parentheses-brackets-braces-and-quotes.md index a55d812d8a..b0a27ebc3e 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-unclosed-parentheses-brackets-braces-and-quotes.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-unclosed-parentheses-brackets-braces-and-quotes.md @@ -1,6 +1,6 @@ --- id: 587d7b84367417b2b2512b36 -title: 'Catch Unclosed Parentheses, Brackets, Braces and Quotes' +title: '捕获未闭合的括号、方括号、大括号和引号' challengeType: 1 forumTopicId: 301190 dashedName: catch-unclosed-parentheses-brackets-braces-and-quotes @@ -8,23 +8,23 @@ dashedName: catch-unclosed-parentheses-brackets-braces-and-quotes # --description-- -Another syntax error to be aware of is that all opening parentheses, brackets, curly braces, and quotes have a closing pair. Forgetting a piece tends to happen when you're editing existing code and inserting items with one of the pair types. Also, take care when nesting code blocks into others, such as adding a callback function as an argument to a method. +要注意的另一个语法错误是所有的小括号、方括号、花括号和引号都必须配对。 当你编辑代码并插入新代码其中带有括号时,很容易忘记括号闭合。 此外,在将代码块嵌套到其他代码块时要小心,例如将回调函数作为参数添加到方法中。 -One way to avoid this mistake is as soon as the opening character is typed, immediately include the closing match, then move the cursor back between them and continue coding. Fortunately, most modern code editors generate the second half of the pair automatically. +避免这种错误的一种方法是,一次性输入完这些符号,然后将光标移回它们之间继续编写。 好在现在大部分编辑器都会帮你自动补全。 # --instructions-- -Fix the two pair errors in the code. +修复代码中的两个符号配对错误。 # --hints-- -Your code should fix the missing piece of the array. +应该修复数组缺少的部分。 ```js assert(code.match(/myArray\s*?=\s*?\[\s*?1\s*?,\s*?2\s*?,\s*?3\s*?\];/g)); ``` -Your code should fix the missing piece of the `.reduce()` method. The console output should show that "Sum of array values is: 6". +应该修复 `.reduce()` 方法缺少的部分。 控制台应该输出 `Sum of array values is: 6`。 ```js assert(arraySum === 6); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-use-of-assignment-operator-instead-of-equality-operator.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-use-of-assignment-operator-instead-of-equality-operator.md index e164f37399..20382d231e 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-use-of-assignment-operator-instead-of-equality-operator.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-use-of-assignment-operator-instead-of-equality-operator.md @@ -1,6 +1,6 @@ --- id: 587d7b85367417b2b2512b38 -title: Catch Use of Assignment Operator Instead of Equality Operator +title: 捕获使用赋值运算符而不是相等运算符 challengeType: 1 forumTopicId: 301191 dashedName: catch-use-of-assignment-operator-instead-of-equality-operator @@ -8,37 +8,39 @@ dashedName: catch-use-of-assignment-operator-instead-of-equality-operator # --description-- -Branching programs, i.e. ones that do different things if certain conditions are met, rely on `if`, `else if`, and `else` statements in JavaScript. The condition sometimes takes the form of testing whether a result is equal to a value. +分支程序,即在满足某些条件时执行不同操作的程序,依赖于 JavaScript 中的`if`,`else if`、`else`语句。 条件有时采取测试一个结果是否等于一个值的形式。 -This logic is spoken (in English, at least) as "if x equals y, then ..." which can literally translate into code using the `=`, or assignment operator. This leads to unexpected control flow in your program. +这种逻辑可以表述为“如果 x 等于 y ,则......”,听起来像是可以使用 `=`(即赋值运算符)。 然而,这会导致程序中流程出问题。 -As covered in previous challenges, the assignment operator (`=`) in JavaScript assigns a value to a variable name. And the `==` and `===` operators check for equality (the triple `===` tests for strict equality, meaning both value and type are the same). +如前面的挑战所述,JavaScript 中的赋值运算符 (`=`) 是用来为变量名赋值的。 并且 `==` 和 `===` 运算符检查相等性(三等号 `===` 是用来测试是否严格相等的,严格相等的意思是值和类型都必须相同)。 -The code below assigns `x` to be 2, which evaluates as `true`. Almost every value on its own in JavaScript evaluates to `true`, except what are known as the "falsy" values: `false`, `0`, `""` (an empty string), `NaN`, `undefined`, and `null`. +下面的代码将 `x` 赋值为 2,表达式会在执行后得到 `true`。 JavaScript 会把大部分的值都视为 `true`,除了所谓的 “falsy”值,即:`false`、`0`、`""`(空字符串)、`NaN`、`undefined` 和 `null`。 ```js let x = 1; let y = 2; if (x = y) { - // this code block will run for any value of y (unless y were originally set as a falsy) + } else { - // this code block is what should run (but won't) in this example + } ``` +在这个示例中,除非 `y` 值是假值,否则当 `y` 为任何值时,`if` 语句中的代码块都会运行。 我们期望运行的 `else` 代码块实际上将不会运行。 + # --instructions-- -Fix the condition so the program runs the right branch, and the appropriate value is assigned to `result`. +修复条件语句,以便程序运行正确的分支,并给 `result` 赋正确的值。 # --hints-- -Your code should fix the condition so it checks for equality, instead of using assignment. +应该修复条件语句,使其判断是否相等,而不是赋值。 ```js assert(result == 'Not equal!'); ``` -The condition should use either `==` or `===` to test for equality. +条件语句可以使用 `==` 或 `===` 来测试是否相等。 ```js assert(code.match(/x\s*?===?\s*?y/g)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/prevent-infinite-loops-with-a-valid-terminal-condition.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/prevent-infinite-loops-with-a-valid-terminal-condition.md index 9455e13645..442bbd6e39 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/prevent-infinite-loops-with-a-valid-terminal-condition.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/prevent-infinite-loops-with-a-valid-terminal-condition.md @@ -1,6 +1,6 @@ --- id: 587d7b86367417b2b2512b3d -title: Prevent Infinite Loops with a Valid Terminal Condition +title: 使用有效的终止条件防止无限循环 challengeType: 1 forumTopicId: 301192 dashedName: prevent-infinite-loops-with-a-valid-terminal-condition @@ -8,9 +8,9 @@ dashedName: prevent-infinite-loops-with-a-valid-terminal-condition # --description-- -The final topic is the dreaded infinite loop. Loops are great tools when you need your program to run a code block a certain number of times or until a condition is met, but they need a terminal condition that ends the looping. Infinite loops are likely to freeze or crash the browser, and cause general program execution mayhem, which no one wants. +最后一个话题是可怕的无限循环。 当需要程序运行代码块一定次数或满足条件时,循环是很好的工具,但是它们需要终止条件来结束循环。 无限循环可能会使浏览器冻结或崩溃,并导致程序执行混乱,没有人想要这样的结果。 -There was an example of an infinite loop in the introduction to this section - it had no terminal condition to break out of the `while` loop inside `loopy()`. Do NOT call this function! +在本节的介绍中有一个无限循环的例子——它没有终止条件来摆脱`loopy()`内的`while`循环。 不要调用这个函数! ```js function loopy() { @@ -20,21 +20,21 @@ function loopy() { } ``` -It's the programmer's job to ensure that the terminal condition, which tells the program when to break out of the loop code, is eventually reached. One error is incrementing or decrementing a counter variable in the wrong direction from the terminal condition. Another one is accidentally resetting a counter or index variable within the loop code, instead of incrementing or decrementing it. +程序员的工作是确保最终达到终止条件,该条件告诉程序何时跳出循环。 有一种错误是从终端条件向错误方向递增或递减计数器变量。 另一种是在循环代码中意外重置计数器或索引变量,而不是递增或递减它。 # --instructions-- -The `myFunc()` function contains an infinite loop because the terminal condition `i != 4` will never evaluate to `false` (and break the looping) - `i` will increment by 2 each pass, and jump right over 4 since `i` is odd to start. Fix the comparison operator in the terminal condition so the loop only runs for `i` less than or equal to 4. +`myFunc()`函数包含一个无限循环,因为终止条件`i != 4`永远不会为`false`(并中断循环) -`i`将每次递增 2,然后跳过 4,因为`i`是从奇数开始递增。 在终端条件中输入比较运算符,使循环仅在`i`小于或等于 4 的情况下运行。 # --hints-- -Your code should change the comparison operator in the terminal condition (the middle part) of the `for` loop. +你应该在`for`循环的终止条件(中间部分)中更改比较运算符。 ```js assert(code.match(/i\s*?<=\s*?4;/g).length == 1); ``` -Your code should fix the comparison operator in the terminal condition of the loop. +你应该修改比较运算符来避免出现死循环。 ```js assert(!code.match(/i\s*?!=\s*?4;/g)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/understanding-the-differences-between-the-freecodecamp-and-browser-console.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/understanding-the-differences-between-the-freecodecamp-and-browser-console.md index 10f47a1581..fb98d4921b 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/understanding-the-differences-between-the-freecodecamp-and-browser-console.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/understanding-the-differences-between-the-freecodecamp-and-browser-console.md @@ -1,6 +1,6 @@ --- id: 587d7b83367417b2b2512b37 -title: Understanding the Differences between the freeCodeCamp and Browser Console +title: 了解 freeCodeCamp 和浏览器控制台之间的差异 challengeType: 1 forumTopicId: 301193 dashedName: understanding-the-differences-between-the-freecodecamp-and-browser-console @@ -8,27 +8,27 @@ dashedName: understanding-the-differences-between-the-freecodecamp-and-browser-c # --description-- -You may have noticed that some freeCodeCamp JavaScript challenges include their own console. This console behaves a little differently than the browser console you used in the last challenge. +你可能已经注意到一些 freeCodeCamp JavaScript 的挑战有自己的控制台。 这些控制台的行为与上一次挑战中使用的浏览器控制台略有不同。 -The following challenge is meant to highlight the main difference between the freeCodeCamp console and your browser console. +以下挑战旨在强调 freeCodeCamp 控制台与浏览器控制台之间的一些差异。 -When you run ordinary JavaScript, the browser's console will display your `console.log()` statements the exact number of times it is called. +当在浏览器中加载并运行 JavaScript 文件时,`console.log()` 语句会在控制台中按照调用的次数准确地打印出要求的内容。 -The freeCodeCamp console will print your `console.log()` statements a short time after the editor detects a change in the script, as well as during testing. +在编辑器检测到脚本中的更改之后,以及测试期间,freeCodeCamp 控制台将打印 `console.log()` 语句。 -The freeCodeCamp console is cleared before the tests are run and, to avoid spam, only prints the logs during the first test (see the note below for exceptions). +在运行测试之前,将清除 freeCodeCamp 控制台,为避免破坏,仅在第一次测试期间打印日志(请参见下面的注释)。 -If you would like to see every log for every test, run the tests, and open the browser console. If you prefer to use the browser console, and want it to mimic the freeCodeCamp console, place `console.clear()` before any other `console` calls, to clear the browser console. +如果你想看到每次测试的日志,运行测试,并打开浏览器控制台。 如果你喜欢使用浏览器控制台,想要它模仿 freeCodeCamp 控制台,请在其他 `console` 调用前加上 `console.clear()`,以清除浏览器控制台。 -**Note:** `console.log`s inside functions are printed to the freeCodeCamp console whenever those functions are called, this can help debugging functions that are called during testing. +**注意:** 每次调用函数时,函数内的 `console.log` 都会被打印到 freeCodeCamp 控制台。 这样可以帮助在测试期间调试函数。 # --instructions-- -First, use `console.log` to log the `output` variable. Then, use `console.clear` to clear the browser console. +首先,使用 `console.log` 打印 `output` 变量。 然后使用 `console.clear` 清除浏览器控制台。 # --hints-- -You should use `console.clear()` to clear the browser console. +应该使用 `console.clear()` 清除浏览器控制台。 ```js assert( @@ -38,7 +38,7 @@ assert( ); ``` -You should use `console.log()` to print the `output` variable. +应该使用 `console.log()` 打印 `output` 变量。 ```js assert(__helpers.removeWhiteSpace(code).match(/console\.log\(output\)/)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/use-caution-when-reinitializing-variables-inside-a-loop.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/use-caution-when-reinitializing-variables-inside-a-loop.md index 19dd59b605..e13e375c3c 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/use-caution-when-reinitializing-variables-inside-a-loop.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/use-caution-when-reinitializing-variables-inside-a-loop.md @@ -1,6 +1,6 @@ --- id: 587d7b86367417b2b2512b3c -title: Use Caution When Reinitializing Variables Inside a Loop +title: 重新初始化循环中的变量时要小心 challengeType: 1 forumTopicId: 301194 dashedName: use-caution-when-reinitializing-variables-inside-a-loop @@ -8,29 +8,29 @@ dashedName: use-caution-when-reinitializing-variables-inside-a-loop # --description-- -Sometimes it's necessary to save information, increment counters, or re-set variables within a loop. A potential issue is when variables either should be reinitialized, and aren't, or vice versa. This is particularly dangerous if you accidentally reset the variable being used for the terminal condition, causing an infinite loop. +有时需要在循环中保存信息以增加计数器或重置变量。 一个潜在的问题是变量什么时候该重新初始化,什么时候不该重新初始化,反之亦然。 如果你不小心重置了用于终止条件的变量,导致无限循环,这将特别危险。 -Printing variable values with each cycle of your loop by using `console.log()` can uncover buggy behavior related to resetting, or failing to reset a variable. +使用`console.log()`在每个循环中打印变量值可以发现与重置相关的错误或者重置变量失败。 # --instructions-- -The following function is supposed to create a two-dimensional array with `m` rows and `n` columns of zeroes. Unfortunately, it's not producing the expected output because the `row` variable isn't being reinitialized (set back to an empty array) in the outer loop. Fix the code so it returns a correct 3x2 array of zeroes, which looks like `[[0, 0], [0, 0], [0, 0]]`. +以下函数应该创建一个具有`m`行和`n`列“零”的二维数组。 不幸的是,它没有产生预期的输出,因为`row`变量没有在外部循环中重新初始化(设置回空数组)。 修改代码,使其正确地返回包含 3 行 2 列“零”的二维数组,即`[[0, 0], [0, 0], [0, 0]]`。 # --hints-- -Your code should set the `matrix` variable to an array holding 3 rows of 2 columns of zeroes each. +应将变量 `matrix` 设置为 3 行 2 列“零”的二维数组。 ```js assert(JSON.stringify(matrix) == '[[0,0],[0,0],[0,0]]'); ``` -The `matrix` variable should have 3 rows. +变量 `matrix` 应有 3 行。 ```js assert(matrix.length == 3); ``` -The `matrix` variable should have 2 columns in each row. +变量 `matrix` 每行应有 2 列。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/use-the-javascript-console-to-check-the-value-of-a-variable.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/use-the-javascript-console-to-check-the-value-of-a-variable.md index eba2284614..d812da7f19 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/use-the-javascript-console-to-check-the-value-of-a-variable.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/use-the-javascript-console-to-check-the-value-of-a-variable.md @@ -1,6 +1,6 @@ --- id: 587d7b83367417b2b2512b33 -title: Use the JavaScript Console to Check the Value of a Variable +title: 使用控制台检查变量值 challengeType: 1 forumTopicId: 18372 dashedName: use-the-javascript-console-to-check-the-value-of-a-variable @@ -8,23 +8,23 @@ dashedName: use-the-javascript-console-to-check-the-value-of-a-variable # --description-- -Both Chrome and Firefox have excellent JavaScript consoles, also known as DevTools, for debugging your JavaScript. +Chrome 和 Firefox 都有出色的 JavaScript 控制台(也称为 DevTools),可以用来调试 JavaScript 代码 -You can find Developer tools in your Chrome's menu or Web Console in Firefox's menu. If you're using a different browser, or a mobile phone, we strongly recommend switching to desktop Firefox or Chrome. +可以在 Chrome 的菜单中找到“开发者工具”或 FireFox 的菜单中的 “Web 控制台”。 如果你使用其他浏览器或手机,我们强烈建议你切换到桌面版 Firefox 或 Chrome。 -The `console.log()` method, which "prints" the output of what's within its parentheses to the console, will likely be the most helpful debugging tool. Placing it at strategic points in your code can show you the intermediate values of variables. It's good practice to have an idea of what the output should be before looking at what it is. Having check points to see the status of your calculations throughout your code will help narrow down where the problem is. +`console.log()` 方法可能是最有用的调试工具,它可以将括号中的内容输出到控制台。 将它放在代码中的关键点可以显示变量在当时的值。 在查看输出之前,最好先想清楚输出应该是什么。 在整个代码中使用检查点来查看计算状态将有助于缩小问题的范围。 -Here's an example to print 'Hello world!' to the console: +下面是输出 `Hello world!` 字符串到控制台的示例: `console.log('Hello world!');` # --instructions-- -Use the `console.log()` method to print the value of the variable `a` where noted in the code. +请使用 `console.log()` 方法在代码中注明的地方输出变量 `a` 的值。 # --hints-- -Your code should use `console.log()` to check the value of the variable `a`. +应使用 `console.log()` 来检查变量 `a` 的值。 ```js assert(code.match(/console\.log\(a\)/g)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/use-typeof-to-check-the-type-of-a-variable.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/use-typeof-to-check-the-type-of-a-variable.md index e9d54bfb66..78dbbc97ca 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/use-typeof-to-check-the-type-of-a-variable.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/use-typeof-to-check-the-type-of-a-variable.md @@ -1,6 +1,6 @@ --- id: 587d7b84367417b2b2512b34 -title: Use typeof to Check the Type of a Variable +title: 使用 type of 检查变量的类型 challengeType: 1 forumTopicId: 18374 dashedName: use-typeof-to-check-the-type-of-a-variable @@ -8,38 +8,40 @@ dashedName: use-typeof-to-check-the-type-of-a-variable # --description-- -You can use `typeof` to check the data structure, or type, of a variable. This is useful in debugging when working with multiple data types. If you think you're adding two numbers, but one is actually a string, the results can be unexpected. Type errors can lurk in calculations or function calls. Be careful especially when you're accessing and working with external data in the form of a JavaScript Object Notation (JSON) object. +可以使用 `typeof` 检查变量的数据结构或类型。 在处理多种数据类型时,这会对调试很有帮助。 如果想计算两数之和,但实际传入了一个字符串参数,则结果可能是错误的。 类型错误可能隐藏在计算或函数调用中。 当你以 JavaScript 对象(JSON)的形式访问和使用外部数据时尤其要小心。 -Here are some examples using `typeof`: +下面是使用 `typeof` 的一些示例: ```js -console.log(typeof ""); // outputs "string" -console.log(typeof 0); // outputs "number" -console.log(typeof []); // outputs "object" -console.log(typeof {}); // outputs "object" +console.log(typeof ""); +console.log(typeof 0); +console.log(typeof []); +console.log(typeof {}); ``` -JavaScript recognizes six primitive (immutable) data types: `Boolean`, `Null`, `Undefined`, `Number`, `String`, and `Symbol` (new with ES6) and one type for mutable items: `Object`. Note that in JavaScript, arrays are technically a type of object. +控制台将按顺序显示字符串 `string`、`number`、`object` 和 `object`。 + +JavaScript 有六种原始(不可变)数据类型:`Boolean`、`Null`、`Undefined`、`Number`、`String` 和 `Symbol`(ES6 中新增的),和一种可变的数据类型:`Object`。 注意:在 JavaScript 中,数组在本质上是一种对象。 # --instructions-- -Add two `console.log()` statements to check the `typeof` each of the two variables `seven` and `three` in the code. +添加两个 `console.log()` 语句来检查代码中的两个变量 `seven` 和 `three` 的 `typeof` 值。 # --hints-- -Your code should use `typeof` in two `console.log()` statements to check the type of the variables. +应在两个 `console.log()` 语句中使用 `typeof` 来检查变量的类型。 ```js assert(code.match(/console\.log\(typeof[\( ].*\)?\)/g).length == 2); ``` -Your code should use `typeof` to check the type of the variable `seven`. +应使用 `typeof` 来检查变量 `seven` 的类型。 ```js assert(code.match(/typeof[\( ]seven\)?/g)); ``` -Your code should use `typeof` to check the type of the variable `three`. +应使用 `typeof` 来检查变量 `three` 的类型。 ```js assert(code.match(/typeof[\( ]three\)?/g)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords.md index ba319ea8bc..da1c1281d9 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords.md @@ -1,6 +1,6 @@ --- id: 587d7b87367417b2b2512b40 -title: Compare Scopes of the var and let Keywords +title: 比较 var 和 let 关键字的作用域 challengeType: 1 forumTopicId: 301195 dashedName: compare-scopes-of-the-var-and-let-keywords @@ -8,11 +8,11 @@ dashedName: compare-scopes-of-the-var-and-let-keywords # --description-- -When you declare a variable with the `var` keyword, it is declared globally, or locally if declared inside a function. +使用 `var` 关键字来声明一个变量的时候,这个变量会被声明成全局变量,或是函数内的局部变量。 -The `let` keyword behaves similarly, but with some extra features. When you declare a variable with the `let` keyword inside a block, statement, or expression, its scope is limited to that block, statement, or expression. +`let` 关键字的作用与此类似,但会有一些额外的特性。 如果在代码块、语句或表达式中使用关键字 `let` 声明变量,这个变量的作用域就被限制在当前的代码块、语句或表达式之中。 -For example: +举个例子: ```js var numArray = []; @@ -20,12 +20,12 @@ for (var i = 0; i < 3; i++) { numArray.push(i); } console.log(numArray); -// returns [0, 1, 2] console.log(i); -// returns 3 ``` -With the `var` keyword, `i` is declared globally. So when `i++` is executed, it updates the global variable. This code is similar to the following: +这里控制台将显示值 `[0, 1, 2]` 和 `3`。 + +因为使用了 `var` 关键字,`i` 被声明为全局变量。 所以当 `i++` 执行时,它会更新全局变量。 这个代码和下方的代码类似: ```js var numArray = []; @@ -34,12 +34,12 @@ for (i = 0; i < 3; i++) { numArray.push(i); } console.log(numArray); -// returns [0, 1, 2] console.log(i); -// returns 3 ``` -This behavior will cause problems if you were to create a function and store it for later use inside a for loop that uses the `i` variable. This is because the stored function will always refer to the value of the updated global `i` variable. +这里控制台将显示值 `[0, 1, 2]` 和 `3`。 + +如果你创建一个函数,将它存储起来,稍后在使用 `i` 变量的 `for` 循环中使用。这么做可能会出现问题。 这是因为存储的函数会总是指向更新后的全局 `i` 变量的值。 ```js var printNumTwo; @@ -51,10 +51,11 @@ for (var i = 0; i < 3; i++) { } } console.log(printNumTwo()); -// returns 3 ``` -As you can see, `printNumTwo()` prints 3 and not 2. This is because the value assigned to `i` was updated and the `printNumTwo()` returns the global `i` and not the value `i` had when the function was created in the for loop. The `let` keyword does not follow this behavior: +这里控制台将显示值 `3`。 + +可以看到,`printNumTwo()` 打印了 3,而不是 2。 这是因为赋值给 `i` 的值已经更新,`printNumTwo()` 返回全局的 `i`,而不是在 for 循环中创建函数时 `i` 的值。 `let` 关键字就不会出现这种现象: ```js let printNumTwo; @@ -66,28 +67,28 @@ for (let i = 0; i < 3; i++) { } } console.log(printNumTwo()); -// returns 2 console.log(i); -// returns "i is not defined" ``` -`i` is not defined because it was not declared in the global scope. It is only declared within the for loop statement. `printNumTwo()` returned the correct value because three different `i` variables with unique values (0, 1, and 2) were created by the `let` keyword within the loop statement. +在这里控制台将显示值 `2` 和一个错误提示 `i is not defined`。 + +`i` 未定义,因为它没有在全局范围内声明。 它只在 `for` 循环语句中被声明。 `printNumTwo()` 返回了正确的值,因为 `let` 关键字在循环语句中使 `i` 变量产生了三个不同的值(分别为 0、1、2)。 # --instructions-- -Fix the code so that `i` declared in the if statement is a separate variable than `i` declared in the first line of the function. Be certain not to use the `var` keyword anywhere in your code. +修改这段代码,使 `if` 语句中声明的 `i` 变量与在函数的第一行声明的 `i` 变量是彼此独立的。 请注意不要在你的代码的任何地方使用 `var` 关键字。 -This exercise is designed to illustrate the difference between how `var` and `let` keywords assign scope to the declared variable. When programming a function similar to the one used in this exercise, it is often better to use different variable names to avoid confusion. +这个练习旨在表明使用 `var` 与 `let` 关键字声明变量时作用域之间的区别。 当编写类似这个练习中的函数的时候,通常来说最好使用不同的变量名,以避免混淆。 # --hints-- -`var` should not exist in code. +代码中不应该出现 `var`。 ```js (getUserInput) => assert(!getUserInput('index').match(/var/g)); ``` -The variable `i` declared in the if statement should equal "block scope". +`if` 语句中声明的变量 `i` 应该等于字符串 `block scope`。 ```js (getUserInput) => @@ -96,7 +97,7 @@ The variable `i` declared in the if statement should equal "block scope". ); ``` -`checkScope()` should return "function scope" +`checkScope()` 应该返回字符串 `function scope`。 ```js assert(checkScope() === 'function scope'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/complete-a-promise-with-resolve-and-reject.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/complete-a-promise-with-resolve-and-reject.md index 171b4f549c..e69a8e8618 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/complete-a-promise-with-resolve-and-reject.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/complete-a-promise-with-resolve-and-reject.md @@ -1,6 +1,6 @@ --- id: 5cdafbc32913098997531680 -title: Complete a Promise with resolve and reject +title: 通过 resolve 和 reject 完成 Promise challengeType: 1 forumTopicId: 301196 dashedName: complete-a-promise-with-resolve-and-reject @@ -8,7 +8,7 @@ dashedName: complete-a-promise-with-resolve-and-reject # --description-- -A promise has three states: `pending`, `fulfilled`, and `rejected`. The promise you created in the last challenge is forever stuck in the `pending` state because you did not add a way to complete the promise. The `resolve` and `reject` parameters given to the promise argument are used to do this. `resolve` is used when you want your promise to succeed, and `reject` is used when you want it to fail. These are methods that take an argument, as seen below. +Promise 有三个状态:`pending`、`fulfilled` 和 `rejected`。 上一个挑战里创建的 promise 一直阻塞在 `pending` 状态里,因为没有调用 promise 的完成方法。 Promise 提供的 `resolve` 和 `reject` 参数就是用来结束 promise 的。 Promise 成功时调用 `resolve`,promise 执行失败时调用 `reject`, 如下文所述,这些方法需要有一个参数。 ```js const myPromise = new Promise((resolve, reject) => { @@ -20,15 +20,15 @@ const myPromise = new Promise((resolve, reject) => { }); ``` -The example above uses strings for the argument of these functions, but it can really be anything. Often, it might be an object, that you would use data from, to put on your website or elsewhere. +上面的示例使用字符串作为这些函数的参数,但参数实际上可以是任何格式。 通常,它可能是一个包含数据的对象,你可以将它放在网站或其他地方。 # --instructions-- -Make the promise handle success and failure. If `responseFromServer` is `true`, call the `resolve` method to successfully complete the promise. Pass `resolve` a string with the value `We got the data`. If `responseFromServer` is `false`, use the `reject` method instead and pass it the string: `Data not received`. +使 promise 可以处理成功和失败情况。 如果 `responseFromServer` 是 `true`,调用 `resolve` 方法使 promise 成功。 给 `resolve` 传递值为 `We got the data` 的字符串。 如果 `responseFromServer` 是 `false`, 使用 `reject` 方法并传入值为 `Data not received` 的字符串。 # --hints-- -`resolve` should be called with the expected string when the `if` condition is `true`. +当 `if` 条件是 `true` 时应该执行 `resolve`。 ```js assert( @@ -40,7 +40,7 @@ assert( ); ``` -`reject` should be called with the expected string when the `if` condition is `false`. +当 `if` 条件是 `false` 时应该执行 `reject`。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-a-javascript-promise.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-a-javascript-promise.md index 5dbc786915..c952955348 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-a-javascript-promise.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-a-javascript-promise.md @@ -1,6 +1,6 @@ --- id: 5cdafbb0291309899753167f -title: Create a JavaScript Promise +title: 创建一个 JavaScript Promise challengeType: 1 forumTopicId: 301197 dashedName: create-a-javascript-promise @@ -8,7 +8,7 @@ dashedName: create-a-javascript-promise # --description-- -A promise in JavaScript is exactly what it sounds like - you use it to make a promise to do something, usually asynchronously. When the task completes, you either fulfill your promise or fail to do so. `Promise` is a constructor function, so you need to use the `new` keyword to create one. It takes a function, as its argument, with two parameters - `resolve` and `reject`. These are methods used to determine the outcome of the promise. The syntax looks like this: +Promise 是异步编程的一种解决方案 - 它在未来的某时会生成一个值。 任务完成,分执行成功和执行失败两种情况。 `Promise` 是构造器函数,需要通过 `new` 关键字来创建。 构造器参数是一个函数,该函数有两个参数 - `resolve` 和 `reject`。 通过它们来判断 promise 的执行结果。 用法如下: ```js const myPromise = new Promise((resolve, reject) => { @@ -18,17 +18,17 @@ const myPromise = new Promise((resolve, reject) => { # --instructions-- -Create a new promise called `makeServerRequest`. Pass in a function with `resolve` and `reject` parameters to the constructor. +创建一个名为 `makeServerRequest` 的 promise。 给构造器函数传入 `resolve` 和 `reject` 两个参数。 # --hints-- -You should assign a promise to a declared variable named `makeServerRequest`. +应该给名为 `makeServerRequest` 的变量指定一个 promise。 ```js assert(makeServerRequest instanceof Promise); ``` -Your promise should receive a function with `resolve` and `reject` as parameters. +promise 应该接收一个函数做为参数,该函数应该包含 `resolve` 和 `reject` 两个参数。 ```js assert( @@ -41,7 +41,9 @@ assert( # --seed-- ## --seed-contents-- + ```js + ``` # --solutions-- diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-a-module-script.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-a-module-script.md index 507602f57d..65a908d7b8 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-a-module-script.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-a-module-script.md @@ -1,6 +1,6 @@ --- id: 5cddbfd622f1a59093ec611d -title: Create a Module Script +title: 创建一个模块脚本 challengeType: 6 forumTopicId: 301198 dashedName: create-a-module-script @@ -8,27 +8,27 @@ dashedName: create-a-module-script # --description-- -JavaScript started with a small role to play on an otherwise mostly HTML web. Today, it’s huge, and some websites are built almost entirely with JavaScript. In order to make JavaScript more modular, clean, and maintainable; ES6 introduced a way to easily share code among JavaScript files. This involves exporting parts of a file for use in one or more other files, and importing the parts you need, where you need them. In order to take advantage of this functionality, you need to create a script in your HTML document with a type of `module`. Here’s an example: +起初,JavaScript 几乎只在 HTML web 扮演一个很小的角色。 今天,一切不同了,很多网站几乎全是用 JavaScript 所写。 为了让 JavaScript 更模块化、更整洁以及更易于维护,ES6 引入了在多个 JavaScript 文件之间共享代码的机制。 它可以导出文件的一部分供其它文件使用,然后在需要它的地方按需导入。 为了使用这一功能, 需要在 HTML 文档里创建一个 `type` 为 `module` 的脚本。 例子如下: ```html ``` -A script that uses this `module` type can now use the `import` and `export` features you will learn about in the upcoming challenges. +使用了 `module` 类型的脚本可以使用 `import` 和 `export` 特性(接下来的挑战会介绍)。 # --instructions-- -Add a script to the HTML document of type `module` and give it the source file of `index.js` +给 HTML 文档添加 `module` 类型的脚本,指定源文件为 `index.js`。 # --hints-- -You should create a `script` tag. +应该创建一个 `script` 标签。 ```js assert(code.match(/<\s*script[^>]*>\s*<\/\s*script\s*>/g)); ``` -Your `script` tag should be of type `module`. +`script` 标签应该有一个值为 `module` 的 `type` 属性。 ```js assert( @@ -38,7 +38,7 @@ assert( ); ``` -Your `script` tag should have a `src` of `index.js`. +`script` 标签的 `src` 属性应该为 `index.js`。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-an-export-fallback-with-export-default.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-an-export-fallback-with-export-default.md index ac32fc0848..23bcce9847 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-an-export-fallback-with-export-default.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-an-export-fallback-with-export-default.md @@ -1,6 +1,6 @@ --- id: 587d7b8c367417b2b2512b58 -title: Create an Export Fallback with export default +title: 用 export default 创建一个默认导出 challengeType: 1 forumTopicId: 301199 dashedName: create-an-export-fallback-with-export-default @@ -8,33 +8,33 @@ dashedName: create-an-export-fallback-with-export-default # --description-- -In the `export` lesson, you learned about the syntax referred to as a named export. This allowed you to make multiple functions and variables available for use in other files. +在 `export` 的课程中,你学习了命名导出语法, 这可以在其他文件中引用一些函数或者变量。 -There is another `export` syntax you need to know, known as export default. Usually you will use this syntax if only one value is being exported from a file. It is also used to create a fallback value for a file or module. +还需要了解另外一种被称为默认导出的 `export` 的语法。 在文件中只有一个值需要导出的时候,通常会使用这种语法。 它也常常用于给文件或者模块创建返回值。 -Below are examples using `export default`: +下面是使用 `export default` 的例子: ```js -// named function export default function add(x, y) { return x + y; } -// anonymous function export default function(x, y) { return x + y; } ``` -Since `export default` is used to declare a fallback value for a module or file, you can only have one value be a default export in each module or file. Additionally, you cannot use `export default` with `var`, `let`, or `const` +第一个是命名函数,第二个是匿名函数。 + +`export default` 用于为模块或文件声明一个返回值,在每个文件或者模块中应当只默认导出一个值。 此外,你不能将 `export default` 与 `var`、`let` 或 `const` 同时使用。 # --instructions-- -The following function should be the fallback value for the module. Please add the necessary code to do so. +下面的函数应该在这个模块中返回一个值。 请添加需要的代码。 # --hints-- -Your code should use `export` fallback. +正确地使用 `export` 返回值。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-strings-using-template-literals.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-strings-using-template-literals.md index cd5c70bd6f..b89eccb84c 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-strings-using-template-literals.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-strings-using-template-literals.md @@ -1,6 +1,6 @@ --- id: 587d7b8a367417b2b2512b4e -title: Create Strings using Template Literals +title: 使用模板字面量创建字符串 challengeType: 1 forumTopicId: 301200 dashedName: create-strings-using-template-literals @@ -8,11 +8,11 @@ dashedName: create-strings-using-template-literals # --description-- -A new feature of ES6 is the template literal. This is a special type of string that makes creating complex strings easier. +模板字符串是 ES6 的另外一项新的功能。 这是一种可以轻松构建复杂字符串的方法。 -Template literals allow you to create multi-line strings and to use string interpolation features to create strings. +模板字符串可以使用多行字符串和字符串插值功能。 -Consider the code below: +请看以下代码: ```js const person = { @@ -20,23 +20,21 @@ const person = { age: 56 }; -// Template literal with multi-line and string interpolation const greeting = `Hello, my name is ${person.name}! I am ${person.age} years old.`; -console.log(greeting); // prints -// Hello, my name is Zodiac Hasbro! -// I am 56 years old. - +console.log(greeting); ``` -A lot of things happened there. Firstly, the example uses backticks (`` ` ``), not quotes (`'` or `"`), to wrap the string. Secondly, notice that the string is multi-line, both in the code and the output. This saves inserting `\n` within strings. The `${variable}` syntax used above is a placeholder. Basically, you won't have to use concatenation with the `+` operator anymore. To add variables to strings, you just drop the variable in a template string and wrap it with `${` and `}`. Similarly, you can include other expressions in your string literal, for example `${a + b}`. This new way of creating strings gives you more flexibility to create robust strings. +控制台将显示字符串 `Hello, my name is Zodiac Hasbro!` 和 `I am 56 years old.`。 + +这里发生了许多事情。 首先,这个例子使用反引号(`` ` ``),而不是引号(`'` 或者 `"`)将字符串括起来。 其次,注意代码和输出中的字符串都是多行的。 不需要在字符串中插入 `\n`。 上面使用的 `${variable}` 语法是一个占位符。 这样一来,你将不再需要使用 `+` 运算符来连接字符串。 当需要在字符串里增加变量的时候,你只需要在变量的外面括上 `${` 和 `}`,并将其放在模板字符串里就可以了。 同样,你可以在字符串中包含其他表达式,例如 `${a + b}`。 这个新的方式使你可以更灵活地创建复杂的字符串。 # --instructions-- -Use template literal syntax with backticks to create an array of list element (`li`) strings. Each list element's text should be one of the array elements from the `failure` property on the `result` object and have a `class` attribute with the value `text-warning`. The `makeList` function should return the array of list item strings. +使用模板字符串的反引号的语法创建一个包含条目(`li`)字符串的数组。 每个条目应该是 `result` 对象 `failure` 属性的数组内的元素,并具有 `class` 属性,值为 `text-warning`。 `makeList` 函数应该返回列表项字符串的数组。 -Use an iterator method (any kind of loop) to get the desired output (shown below). +使用遍历方法(可以是任意形式的循环)输出指定值(如下)。 ```js [ @@ -48,7 +46,7 @@ Use an iterator method (any kind of loop) to get the desired output (shown below # --hints-- -`failuresList` should be an array containing `result failure` messages. +`failuresList` 应该是一个包含了 `result failure` 信息的数组。 ```js assert( @@ -56,7 +54,7 @@ assert( ); ``` -`failuresList` should be equal to the specified output. +`failuresList` 应该输出指定的值。 ```js assert( @@ -68,13 +66,13 @@ assert( ); ``` -Template strings and expression interpolation should be used. +应使用模板字符串和表达式内插。 ```js (getUserInput) => assert(getUserInput('index').match(/(`.*\${.*}.*`)/)); ``` -An iterator should be used. +应该使用遍历。 ```js (getUserInput) => diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/declare-a-read-only-variable-with-the-const-keyword.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/declare-a-read-only-variable-with-the-const-keyword.md index a869196788..332e86774e 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/declare-a-read-only-variable-with-the-const-keyword.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/declare-a-read-only-variable-with-the-const-keyword.md @@ -1,6 +1,6 @@ --- id: 587d7b87367417b2b2512b41 -title: Declare a Read-Only Variable with the const Keyword +title: 用 const 关键字声明只读变量 challengeType: 1 forumTopicId: 301201 dashedName: declare-a-read-only-variable-with-the-const-keyword @@ -8,44 +8,46 @@ dashedName: declare-a-read-only-variable-with-the-const-keyword # --description-- -The keyword `let` is not the only new way to declare variables. In ES6, you can also declare variables using the `const` keyword. +`let` 并不是唯一的新的声明变量的方式。 在 ES6 里面,你还可以使用 `const` 关键字来声明变量。 -`const` has all the awesome features that `let` has, with the added bonus that variables declared using `const` are read-only. They are a constant value, which means that once a variable is assigned with `const`, it cannot be reassigned. +`const` 拥有 `let` 的所有优点,不同的是,通过 `const` 声明的变量是只读的。 这意味着通过 `const` 声明的变量只能被赋值一次,而不能被再次赋值。 ```js const FAV_PET = "Cats"; -FAV_PET = "Dogs"; // returns error +FAV_PET = "Dogs"; ``` -As you can see, trying to reassign a variable declared with `const` will throw an error. You should always name variables you don't want to reassign using the `const` keyword. This helps when you accidentally attempt to reassign a variable that is meant to stay constant. A common practice when naming constants is to use all uppercase letters, with words separated by an underscore. +控制台将由于给 `FAV_PET` 重新赋值而显示错误。 -**Note:** It is common for developers to use uppercase variable identifiers for immutable values and lowercase or camelCase for mutable values (objects and arrays). In a later challenge you will see an example of a lowercase variable identifier being used for an array. +可见,尝试给用 `const` 声明的变量重新赋值会报错。 你应该使用 `const` 关键字来声明所有不打算再次赋值的变量。 这有助于避免给一个常量进行额外的再次赋值。 一个最佳实践是对所有常量的命名采用全大写字母,并在单词之间使用下划线进行分隔。 + +**注意:**通常,开发者会用大写字母作为常量标识符,用小写字母或者驼峰命名作为变量(对象或数组)标识符。 后面的挑战会涉及到在数组中使用小写变量标识符。 # --instructions-- -Change the code so that all variables are declared using `let` or `const`. Use `let` when you want the variable to change, and `const` when you want the variable to remain constant. Also, rename variables declared with `const` to conform to common practices, meaning constants should be in all caps. +改变以下代码,使得所有的变量都使用 `let` 或 `const` 关键词来声明。 当变量将会改变的时候使用 `let` 关键字,当变量要保持常量的时候使用 `const` 关键字。 同时,对使用 `const` 声明的变量按照最佳实践重命名,变量名中的字母应该都是大写的。 # --hints-- -`var` should not exist in your code. +代码中不应有 `var`。 ```js (getUserInput) => assert(!getUserInput('index').match(/var/g)); ``` -`SENTENCE` should be a constant variable declared with `const`. +`SENTENCE` 应该是使用 `const` 声明的常量。 ```js (getUserInput) => assert(getUserInput('index').match(/(const SENTENCE)/g)); ``` -`i` should be declared with `let`. +`i` 应该是使用 `let`声明的。 ```js (getUserInput) => assert(getUserInput('index').match(/(let i)/g)); ``` -`console.log` should be changed to print the `SENTENCE` variable. +`console.log` 应该修改为用于打印 `SENTENCE` 变量。 ```js (getUserInput) => diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/explore-differences-between-the-var-and-let-keywords.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/explore-differences-between-the-var-and-let-keywords.md index 7792ee384b..220c5a7c99 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/explore-differences-between-the-var-and-let-keywords.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/explore-differences-between-the-var-and-let-keywords.md @@ -1,6 +1,6 @@ --- id: 587d7b87367417b2b2512b3f -title: Explore Differences Between the var and let Keywords +title: 探索 var 和 let 关键字之间的差异 challengeType: 1 forumTopicId: 301202 dashedName: explore-differences-between-the-var-and-let-keywords @@ -8,49 +8,52 @@ dashedName: explore-differences-between-the-var-and-let-keywords # --description-- -One of the biggest problems with declaring variables with the `var` keyword is that you can overwrite variable declarations without an error. +使用 `var` 关键字来声明变量,会出现重复声明导致变量被覆盖却不会报错的问题。 ```js var camper = 'James'; var camper = 'David'; console.log(camper); -// logs 'David' ``` -As you can see in the code above, the `camper` variable is originally declared as `James` and then overridden to be `David`. In a small application, you might not run into this type of problem, but when your code becomes larger, you might accidentally overwrite a variable that you did not intend to overwrite. Because this behavior does not throw an error, searching and fixing bugs becomes more difficult. -A new keyword called `let` was introduced in ES6 to solve this potential issue with the `var` keyword. If you were to replace `var` with `let` in the variable declarations of the code above, the result would be an error. +这里控制台将显示字符串 `David`。 + +在上面的代码中,`camper` 变量的初始值为 `James`,然后又被覆盖成了 `David`。 在小型的应用中,你可能不会遇到这样的问题。但是当你的代码规模变得更加庞大的时候,就可能会在不经意间覆盖了之前定义的变量。 因为这样的情况不会报错,所以搜索和修复 bug 会变得非常困难。 +在 ES6 中引入了新的关键字 `let` 来解决 `var` 关键字带来的潜在问题。 如果你在上面的代码中使用 `let` 关键字来代替 `var` 关键字,结果会是一个报错。 ```js let camper = 'James'; -let camper = 'David'; // throws an error +let camper = 'David'; ``` -This error can be seen in the console of your browser. So unlike `var`, when using `let`, a variable with the same name can only be declared once. Note the `"use strict"`. This enables Strict Mode, which catches common coding mistakes and "unsafe" actions. For instance: +你可以在浏览器的控制台里看见这个错误。 与 `var` 不同的是,当使用 `let` 的时候,同一名字的变量只能被声明一次。 请注意 `"use strict"`。 这代表着开启了严格模式,用于检测常见的代码错误以及“不安全”的行为, 例如: ```js "use strict"; -x = 3.14; // throws an error because x is not declared +x = 3.14; ``` +这将显示一个错误 `x is not defined`。 + # --instructions-- -Update the code so it only uses the `let` keyword. +请更新这段代码,只使用 `let` 关键字。 # --hints-- -`var` should not exist in the code. +代码中不应有 `var` ```js (getUserInput) => assert(!getUserInput('index').match(/var/g)); ``` -`catName` should be `Oliver`. +`catName` 变量的值应该为 `Oliver` ```js assert(catName === 'Oliver'); ``` -`quote` should be `"Oliver says Meow!"` +`quote` 变量的值应该为 `Oliver says Meow!` ```js assert(quote === 'Oliver says Meow!'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/handle-a-fulfilled-promise-with-then.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/handle-a-fulfilled-promise-with-then.md index e39dd1da26..3609bbc3a4 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/handle-a-fulfilled-promise-with-then.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/handle-a-fulfilled-promise-with-then.md @@ -1,6 +1,6 @@ --- id: 5cdafbd72913098997531681 -title: Handle a Fulfilled Promise with then +title: 用 then 处理 Promise 完成的情况 challengeType: 1 forumTopicId: 301203 dashedName: handle-a-fulfilled-promise-with-then @@ -8,23 +8,23 @@ dashedName: handle-a-fulfilled-promise-with-then # --description-- -Promises are most useful when you have a process that takes an unknown amount of time in your code (i.e. something asynchronous), often a server request. When you make a server request it takes some amount of time, and after it completes you usually want to do something with the response from the server. This can be achieved by using the `then` method. The `then` method is executed immediately after your promise is fulfilled with `resolve`. Here’s an example: +当程序需要花费未知的时间才能完成时(比如一些异步操作),一般是服务器请求,promise 很有用。 服务器请求会花费一些时间,当结束时,需要根据服务器的响应执行一些操作。 这可以用 `then` 方法来实现, 当 promise 完成 `resolve` 时会触发 `then` 方法。 例子如下: ```js myPromise.then(result => { - // do something with the result. + }); ``` -`result` comes from the argument given to the `resolve` method. +`result` 即传入 `resolve` 方法的参数。 # --instructions-- -Add the `then` method to your promise. Use `result` as the parameter of its callback function and log `result` to the console. +给 promise 添加 `then` 方法。 用 `result` 做为回调函数的参数并将 `result` 打印在控制台。 # --hints-- -You should call the `then` method on the promise. +应该给 promise 方法调用 `then` 方法。 ```js assert( @@ -32,13 +32,13 @@ assert( ); ``` -Your `then` method should have a callback function with `result` as its parameter. +`then` 方法应该有一个回调函数,回调函数参数为 `result`。 ```js assert(resultIsParameter); ``` -You should log `result` to the console. +应该打印 `result` 到控制台。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/handle-a-rejected-promise-with-catch.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/handle-a-rejected-promise-with-catch.md index 815c4b4786..78fc588df0 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/handle-a-rejected-promise-with-catch.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/handle-a-rejected-promise-with-catch.md @@ -1,6 +1,6 @@ --- id: 5cdafbe72913098997531682 -title: Handle a Rejected Promise with catch +title: 使用 catch 处理 Promise 失败的情况 challengeType: 1 forumTopicId: 301204 dashedName: handle-a-rejected-promise-with-catch @@ -8,23 +8,23 @@ dashedName: handle-a-rejected-promise-with-catch # --description-- -`catch` is the method used when your promise has been rejected. It is executed immediately after a promise's `reject` method is called. Here’s the syntax: +当 promise 失败时会调用 `catch` 方法。 当 promise 的 `reject` 方法执行时会直接调用。 用法如下: ```js myPromise.catch(error => { - // do something with the error. + }); ``` -`error` is the argument passed in to the `reject` method. +`error` 是传入 `reject` 方法的参数。 # --instructions-- -Add the `catch` method to your promise. Use `error` as the parameter of its callback function and log `error` to the console. +给 promise 添加 `catch` 方法。 用 `error` 作为回调函数的参数,并把 `error` 打印到控制台。 # --hints-- -You should call the `catch` method on the promise. +应该在 promise 上调用 `catch` 方法。 ```js assert( @@ -32,13 +32,13 @@ assert( ); ``` -Your `catch` method should have a callback function with `error` as its parameter. +`catch` 方法应该有一个回调函数,回调函数参数为 `error`。 ```js assert(errorIsParameter); ``` -You should log `error` to the console. +应该打印 `error` 到控制台。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/import-a-default-export.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/import-a-default-export.md index d8a0a3d465..f14498a0bc 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/import-a-default-export.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/import-a-default-export.md @@ -1,6 +1,6 @@ --- id: 587d7b8d367417b2b2512b59 -title: Import a Default Export +title: 导入一个默认的导出 challengeType: 1 forumTopicId: 301205 dashedName: import-a-default-export @@ -8,21 +8,21 @@ dashedName: import-a-default-export # --description-- -In the last challenge, you learned about `export default` and its uses. To import a default export, you need to use a different `import` syntax. In the following example, `add` is the default export of the `math_functions.js` file. Here is how to import it: +在上一个挑战里,学习了 `export default` 的用法。 还需要一种 `import` 的语法来导入默认的导出。 在下面的例子里,`add` 是 `math_functions.js` 文件的默认导出。 以下是如何导入它: ```js import add from "./math_functions.js"; ``` -The syntax differs in one key place. The imported value, `add`, is not surrounded by curly braces (`{}`). `add` here is simply a variable name for whatever the default export of the `math_functions.js` file is. You can use any name here when importing a default. +这个语法有一处特别的地方, 被导入的 `add` 值没有被花括号(`{}`)所包围。 `add` 只是一个变量的名字,对应 `math_functions.js` 文件的任何默认导出值。 在导入默认导出时,可以使用任何名字。 # --instructions-- -In the following code, import the default export from the `math_functions.js` file, found in the same directory as this file. Give the import the name `subtract`. +在下面的代码中,导入同一目录中 `math_functions.js` 文件的默认导出。 导入变量的名字为 `subtract`。 # --hints-- -You should properly import `subtract` from `math_functions.js`. +应从 `math_functions.js` 中正确导入 `subtract`。 ```js assert(code.match(/import\s+subtract\s+from\s+('|")\.\/math_functions\.js\1/g)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/mutate-an-array-declared-with-const.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/mutate-an-array-declared-with-const.md index 90799c6bba..da1975e0a4 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/mutate-an-array-declared-with-const.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/mutate-an-array-declared-with-const.md @@ -1,6 +1,6 @@ --- id: 587d7b87367417b2b2512b42 -title: Mutate an Array Declared with const +title: 改变一个用 const 声明的数组 challengeType: 1 forumTopicId: 301206 dashedName: mutate-an-array-declared-with-const @@ -8,40 +8,42 @@ dashedName: mutate-an-array-declared-with-const # --description-- -The `const` declaration has many use cases in modern JavaScript. +在现代的 JavaScript 里,`const` 声明有很多用法。 -Some developers prefer to assign all their variables using `const` by default, unless they know they will need to reassign the value. Only in that case, they use `let`. +一些开发者倾向于默认使用 `const` 来声明所有变量,除非他们打算后续重新给变量赋值, 那么他们在声明的时候就会用 `let`。 -However, it is important to understand that objects (including arrays and functions) assigned to a variable using `const` are still mutable. Using the `const` declaration only prevents reassignment of the variable identifier. +然而,你要注意,对象(包括数组和函数)在使用 `const` 声明的时候依然是可变的。 使用 `const` 来声明只会保证变量不会被重新赋值。 ```js const s = [5, 6, 7]; -s = [1, 2, 3]; // throws error, trying to assign a const -s[2] = 45; // works just as it would with an array declared with var or let -console.log(s); // returns [5, 6, 45] +s = [1, 2, 3]; +s[2] = 45; +console.log(s); ``` -As you can see, you can mutate the object `[5, 6, 7]` itself and the variable `s` will still point to the altered array `[5, 6, 45]`. Like all arrays, the array elements in `s` are mutable, but because `const` was used, you cannot use the variable identifier `s` to point to a different array using the assignment operator. +`s = [1, 2, 3]` 会导致一个错误。 `console.log` 会显示值 `[5, 6, 45]`。 + +可以发现,你可以改变对象 `[5, 6, 7]` 本身,而变量 `s` 会指向改变后的数组 `[5, 6, 45]`。 和所有数组一样,数组 `s` 中的元素是可以被改变的,但是因为使用了 `const` 关键字,你不能使用赋值操作符将变量标识 `s` 指向另外一个数组。 # --instructions-- -An array is declared as `const s = [5, 7, 2]`. Change the array to `[2, 5, 7]` using various element assignments. +这里有一个使用 `const s = [5, 7, 2]` 声明的数组。 使用对各元素赋值的方法将数组改成 `[2, 5, 7]`。 # --hints-- -You should not replace `const` keyword. +不要替换 `const` 关键字。 ```js (getUserInput) => assert(getUserInput('index').match(/const/g)); ``` -`s` should be a constant variable (by using `const`). +`s` 应该为常量(使用 `const`)。 ```js (getUserInput) => assert(getUserInput('index').match(/const\s+s/g)); ``` -You should not change the original array declaration. +不要改变原数组的声明。 ```js (getUserInput) => @@ -52,7 +54,7 @@ You should not change the original array declaration. ); ``` -`s` should be equal to `[2, 5, 7]`. +`s` 应该等于 `[2, 5, 7]`。 ```js assert.deepEqual(s, [2, 5, 7]); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/prevent-object-mutation.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/prevent-object-mutation.md index fb97d40308..356eee60c1 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/prevent-object-mutation.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/prevent-object-mutation.md @@ -1,6 +1,6 @@ --- id: 598f48a36c8c40764b4e52b3 -title: Prevent Object Mutation +title: 防止对象改变 challengeType: 1 forumTopicId: 301207 dashedName: prevent-object-mutation @@ -8,9 +8,9 @@ dashedName: prevent-object-mutation # --description-- -As seen in the previous challenge, `const` declaration alone doesn't really protect your data from mutation. To ensure your data doesn't change, JavaScript provides a function `Object.freeze` to prevent data mutation. +通过之前的挑战可以看出,`const` 声明并不会真的保护数据不被改变。 为了确保数据不被改变,JavaScript 提供了一个函数 `Object.freeze`。 -Once the object is frozen, you can no longer add, update, or delete properties from it. Any attempt at changing the object will be rejected without an error. +当一个对象被冻结的时候,你不能再对它的属性再进行增、删、改的操作。 任何试图改变对象的操作都会被阻止,却不会报错。 ```js let obj = { @@ -18,32 +18,33 @@ let obj = { review:"Awesome" }; Object.freeze(obj); -obj.review = "bad"; // will be ignored. Mutation not allowed -obj.newProp = "Test"; // will be ignored. Mutation not allowed +obj.review = "bad"; +obj.newProp = "Test"; console.log(obj); -// { name: "FreeCodeCamp", review:"Awesome"} ``` +`obj.review` 和 `obj.newProp` 赋值将导致错误,控制台将显示值 `{ name: "FreeCodeCamp", review: "Awesome" }`。 + # --instructions-- -In this challenge you are going to use `Object.freeze` to prevent mathematical constants from changing. You need to freeze the `MATH_CONSTANTS` object so that no one is able to alter the value of `PI`, add, or delete properties. +在这个挑战中,你将使用 `Object.freeze` 来防止数学常量被改变。 你需要冻结 `MATH_CONSTANTS` 对象,使得没有人可以改变 `PI` 的值,或增加或删除属性。 # --hints-- -You should not replace `const` keyword. +不要替换 `const` 关键字。 ```js (getUserInput) => assert(getUserInput('index').match(/const/g)); ``` -`MATH_CONSTANTS` should be a constant variable (by using `const`). +`MATH_CONSTANTS` 应该为一个常量(使用 `const`)。 ```js (getUserInput) => assert(getUserInput('index').match(/const\s+MATH_CONSTANTS/g)); ``` -You should not change original `MATH_CONSTANTS`. +不要改变 `MATH_CONSTANTS` 的原始声明。 ```js (getUserInput) => @@ -54,7 +55,7 @@ You should not change original `MATH_CONSTANTS`. ); ``` -`PI` should equal `3.14`. +`PI` 应等于 `3.14`。 ```js assert(PI === 3.14); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/reuse-javascript-code-using-import.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/reuse-javascript-code-using-import.md index ff3449dd2f..7b68385b12 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/reuse-javascript-code-using-import.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/reuse-javascript-code-using-import.md @@ -1,6 +1,6 @@ --- id: 587d7b8c367417b2b2512b55 -title: Reuse JavaScript Code Using import +title: 通过 import 复用 JavaScript 代码 challengeType: 1 forumTopicId: 301208 dashedName: reuse-javascript-code-using-import @@ -8,15 +8,15 @@ dashedName: reuse-javascript-code-using-import # --description-- -`import` allows you to choose which parts of a file or module to load. In the previous lesson, the examples exported `add` from the `math_functions.js` file. Here's how you can import it to use in another file: +`import` 可以导入文件或模块的一部分。 在之前的课程里,例子从 `math_functions.js` 文件里导出了 `add`。 下面看一下如何在其它文件导入它: ```js import { add } from './math_functions.js'; ``` -Here, `import` will find `add` in `math_functions.js`, import just that function for you to use, and ignore the rest. The `./` tells the import to look for the `math_functions.js` file in the same folder as the current file. The relative file path (`./`) and file extension (`.js`) are required when using import in this way. +在这里,`import` 会在 `math_functions.js` 里找到 `add`,只导入这个函数,忽略剩余的部分。 `./` 告诉程序在当前文件的相同目录寻找 `math_functions.js` 文件。 用这种方式导入时,相对路径(`./`)和文件扩展名(`.js`)都是必需的。 -You can import more than one item from the file by adding them in the `import` statement like this: +通过在 `import` 语句里添加项目,可以从文件里导入多个项目,如下: ```js import { add, subtract } from './math_functions.js'; @@ -24,11 +24,11 @@ import { add, subtract } from './math_functions.js'; # --instructions-- -Add the appropriate `import` statement that will allow the current file to use the `uppercaseString` and `lowercaseString` functions you exported in the previous lesson. These functions are in a file called `string_functions.js`, which is in the same directory as the current file. +添加 `import` 语句,使当前文件可以使用你在之前课程里导出的 `uppercaseString` 和 `lowercaseString` 函数。 函数在当前路径下的 `string_functions.js` 文件里。 # --hints-- -You should properly import `uppercaseString`. +应该导入 `uppercaseString`。 ```js assert( @@ -38,7 +38,7 @@ assert( ); ``` -You should properly import `lowercaseString`. +应该导入 `lowercaseString`。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions.md index b804b67af1..753d97b180 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions.md @@ -1,6 +1,6 @@ --- id: 587d7b88367417b2b2512b46 -title: Set Default Parameters for Your Functions +title: 设置函数的默认参数 challengeType: 1 forumTopicId: 301209 dashedName: set-default-parameters-for-your-functions @@ -8,38 +8,40 @@ dashedName: set-default-parameters-for-your-functions # --description-- -In order to help us create more flexible functions, ES6 introduces default parameters for functions. +ES6 里允许给函数传入默认参数,来构建更加灵活的函数。 -Check out this code: +请看以下代码: ```js const greeting = (name = "Anonymous") => "Hello " + name; -console.log(greeting("John")); // Hello John -console.log(greeting()); // Hello Anonymous +console.log(greeting("John")); +console.log(greeting()); ``` -The default parameter kicks in when the argument is not specified (it is undefined). As you can see in the example above, the parameter `name` will receive its default value `"Anonymous"` when you do not provide a value for the parameter. You can add default values for as many parameters as you want. +控制台将显示字符串 `Hello John` 和 `Hello Anonymous`。 + +默认参数会在参数没有被指定(值为 undefined)的时候起作用。 在上面的例子中,参数 `name` 会在没有得到新的值的时候,默认使用值 `Anonymous`。 你还可以给多个参数赋予默认值。 # --instructions-- -Modify the function `increment` by adding default parameters so that it will add 1 to `number` if `value` is not specified. +给函数 `increment` 加上默认参数,使得在 `value` 没有被赋值的时候,默认给 `number` 加上 1。 # --hints-- -The result of `increment(5, 2)` should be `7`. +`increment(5, 2)` 的结果应该是 `7`。 ```js assert(increment(5, 2) === 7); ``` -The result of `increment(5)` should be `6`. +`increment(5)` 的结果应该是 `6`。 ```js assert(increment(5) === 6); ``` -A default parameter value of `1` should be used for `value`. +参数 `value` 的默认值是 `1`。 ```js assert(code.match(/value\s*=\s*1/g)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use--to-import-everything-from-a-file.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use--to-import-everything-from-a-file.md index a175f32383..8abbb1f7fa 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use--to-import-everything-from-a-file.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use--to-import-everything-from-a-file.md @@ -1,6 +1,6 @@ --- id: 587d7b8c367417b2b2512b57 -title: Use * to Import Everything from a File +title: 用 * 从文件中导入所有内容 challengeType: 1 forumTopicId: 301210 dashedName: use--to-import-everything-from-a-file @@ -8,13 +8,13 @@ dashedName: use--to-import-everything-from-a-file # --description-- -Suppose you have a file and you wish to import all of its contents into the current file. This can be done with the `import * as` syntax. Here's an example where the contents of a file named `math_functions.js` are imported into a file in the same directory: +假设你有一个文件,你希望将其所有内容导入到当前文件中。 可以用 `import * as` 语法来实现。 下面是一个从同目录下的 `math_functions.js` 文件中导入所有内容的例子: ```js import * as myMathModule from "./math_functions.js"; ``` -The above `import` statement will create an object called `myMathModule`. This is just a variable name, you can name it anything. The object will contain all of the exports from `math_functions.js` in it, so you can access the functions like you would any other object property. Here's how you can use the `add` and `subtract` functions that were imported: +上面的 `import` 语句会创建一个叫作 `myMathModule` 的对象。 这只是一个变量名,可以随便命名。 对象包含 `math_functions.js` 文件里的所有导出,可以像访问对象的属性那样访问里面的函数。 下面是使用导入的 `add` 和 `subtract` 函数的例子: ```js myMathModule.add(2,3); @@ -23,11 +23,11 @@ myMathModule.subtract(5,3); # --instructions-- -The code in this file requires the contents of the file: `string_functions.js`, that is in the same directory as the current file. Use the `import * as` syntax to import everything from the file into an object called `stringFunctions`. +下面的代码需要从同目录下的 `string_functions.js` 文件中导入所有内容。 使用 `import * as` 语法将文件的所有内容导入对象 `stringFunctions`。 # --hints-- -Your code should properly use `import * as` syntax. +正确使用 `import * as` 语法。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-arrow-functions-to-write-concise-anonymous-functions.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-arrow-functions-to-write-concise-anonymous-functions.md index b1e92a91d2..3130b7d1b9 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-arrow-functions-to-write-concise-anonymous-functions.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-arrow-functions-to-write-concise-anonymous-functions.md @@ -1,6 +1,6 @@ --- id: 587d7b87367417b2b2512b43 -title: Use Arrow Functions to Write Concise Anonymous Functions +title: 使用箭头函数编写简洁的匿名函数 challengeType: 1 forumTopicId: 301211 dashedName: use-arrow-functions-to-write-concise-anonymous-functions @@ -8,9 +8,9 @@ dashedName: use-arrow-functions-to-write-concise-anonymous-functions # --description-- -In JavaScript, we often don't need to name our functions, especially when passing a function as an argument to another function. Instead, we create inline functions. We don't need to name these functions because we do not reuse them anywhere else. +在 JavaScript 里,我们会经常遇到不需要给函数命名的情况,尤其是在需要将一个函数作为参数传给另外一个函数的时候。 这时,我们会创建匿名函数。 因为这些函数不会在其他地方复用,所以我们不需要给它们命名。 -To achieve this, we often use the following syntax: +这种情况下,我们通常会使用以下语法: ```js const myFunc = function() { @@ -19,7 +19,7 @@ const myFunc = function() { } ``` -ES6 provides us with the syntactic sugar to not have to write anonymous functions this way. Instead, you can use **arrow function syntax**: +ES6 提供了其他写匿名函数的方式的语法糖。 你可以使用**箭头函数**: ```js const myFunc = () => { @@ -28,45 +28,45 @@ const myFunc = () => { } ``` -When there is no function body, and only a return value, arrow function syntax allows you to omit the keyword `return` as well as the brackets surrounding the code. This helps simplify smaller functions into one-line statements: +当不需要函数体,只返回一个值的时候,箭头函数允许你省略 `return` 关键字和外面的大括号。 这样就可以将一个简单的函数简化成一个单行语句。 ```js const myFunc = () => "value"; ``` -This code will still return the string `value` by default. +这段代码默认会返回字符串 `value`。 # --instructions-- -Rewrite the function assigned to the variable `magic` which returns a `new Date()` to use arrow function syntax. Also, make sure nothing is defined using the keyword `var`. +使用箭头函数的语法重写赋给 `magic` 变量的函数,使其返回一个新的 Date() `new Date()`。 同时不要用 `var` 关键字来定义任何变量。 # --hints-- -User should replace `var` keyword. +应该替换 `var` 关键字。 ```js (getUserInput) => assert(!getUserInput('index').match(/var/g)); ``` -`magic` should be a constant variable (by using `const`). +`magic` 应该为一个常量(使用 `const`)。 ```js (getUserInput) => assert(getUserInput('index').match(/const\s+magic/g)); ``` -`magic` should be a `function`. +`magic` 应该是一个函数 `function`。 ```js assert(typeof magic === 'function'); ``` -`magic()` should return correct date. +`magic()` 应该返回正确的日期。 ```js assert(magic().setHours(0, 0, 0, 0) === new Date().setHours(0, 0, 0, 0)); ``` -`function` keyword should not be used. +不要使用 `function` 关键字。 ```js (getUserInput) => assert(!getUserInput('index').match(/function/g)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function.md index 9e27796ab3..636aedb488 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function.md @@ -1,6 +1,6 @@ --- id: 587d7b8b367417b2b2512b53 -title: Use class Syntax to Define a Constructor Function +title: 使用 class 语法定义构造函数 challengeType: 1 forumTopicId: 301212 dashedName: use-class-syntax-to-define-a-constructor-function @@ -8,11 +8,11 @@ dashedName: use-class-syntax-to-define-a-constructor-function # --description-- -ES6 provides a new syntax to create objects, using the class keyword. +ES6 提供了一个新的创建对象的语法,使用关键字 class。 -It should be noted that the `class` syntax is just syntax, and not a full-fledged class-based implementation of an object-oriented paradigm, unlike in languages such as Java, Python, Ruby, etc. +值得注意的是,`class` 只是一个语法糖,它并不像 Java、Python 或者 Ruby 这一类的语言一样,严格履行了面向对象的开发规范。 -In ES5, we usually define a constructor function and use the `new` keyword to instantiate an object. +在 ES5 里面,我们通常会定义一个构造函数 `constructor`,然后使用 `new` 关键字来实例化一个对象: ```js var SpaceShuttle = function(targetPlanet){ @@ -21,7 +21,7 @@ var SpaceShuttle = function(targetPlanet){ var zeus = new SpaceShuttle('Jupiter'); ``` -The `class` syntax simply replaces the constructor function creation: +`class` 语法只是简单地替换了构造函数 `constructor` 的写法: ```js class SpaceShuttle { @@ -32,21 +32,21 @@ class SpaceShuttle { const zeus = new SpaceShuttle('Jupiter'); ``` -It should be noted that the `class` keyword declares a new function, to which a constructor is added. This constructor is invoked when `new` is called to create a new object. -**Notes:** +应该注意 `class` 关键字声明了一个新的函数,里面添加了一个构造函数。 当用 `new` 创建一个新的对象时,构造函数会被调用。 -- UpperCamelCase should be used by convention for ES6 class names, as in `SpaceShuttle` used above. -- The constructor method is a special method for creating and initializing an object created with a class. You will learn more about it in the Object Oriented Programming section of the JavaScript Algorithms And Data Structures Certification. +**注意:**首字母大写驼峰命名法 UpperCamelCase 是 ES6 class 命名的惯例,就像上面的 `SpaceShuttle`。 + +`constructor` 方法是一个特殊方法,用于创建和初始化 class 创建的对象。 在 JavaScript 算法和数据结构认证的面向对象编程章节里会更深入介绍它。 # --instructions-- -Use the `class` keyword and write a constructor to create the `Vegetable` class. +使用 `class` 关键词,写一个 `constructor` 来创建 `Vegetable` class。 -The `Vegetable` class allows you to create a vegetable object with a property `name` that gets passed to the constructor. +`Vegetable` 这个 class 可以创建 vegetable 对象,这个对象拥有一个在 `constructor` 中赋值的 `name` 属性。 # --hints-- -`Vegetable` should be a `class` with a defined `constructor` method. +`Vegetable` 应该是一个 `class`,并在其中定义了 `constructor`。 ```js assert( @@ -54,13 +54,13 @@ assert( ); ``` -`class` keyword should be used. +应使用 `class` 关键字。 ```js assert(code.match(/class/g)); ``` -`Vegetable` should be able to be instantiated. +`Vegetable` 可以被实例化。 ```js assert(() => { @@ -69,7 +69,7 @@ assert(() => { }); ``` -`carrot.name` should return `carrot`. +`carrot.name` 应该返回 `carrot`。 ```js assert(carrot.name == 'carrot'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-arrays.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-arrays.md index 1c13043c13..051c5a941b 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-arrays.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-arrays.md @@ -1,6 +1,6 @@ --- id: 587d7b89367417b2b2512b4b -title: Use Destructuring Assignment to Assign Variables from Arrays +title: 使用解构赋值从数组中分配变量 challengeType: 1 forumTopicId: 301213 dashedName: use-destructuring-assignment-to-assign-variables-from-arrays @@ -8,43 +8,47 @@ dashedName: use-destructuring-assignment-to-assign-variables-from-arrays # --description-- -ES6 makes destructuring arrays as easy as destructuring objects. +在 ES6 里面,解构数组可以如同解构对象一样简单。 -One key difference between the spread operator and array destructuring is that the spread operator unpacks all contents of an array into a comma-separated list. Consequently, you cannot pick or choose which elements you want to assign to variables. +与数组解构不同,数组的扩展运算会将数组里的所有内容分解成一个由逗号分隔的列表。 所以,你不能选择哪个元素来给变量赋值。 -Destructuring an array lets us do exactly that: +而对数组进行解构却可以让我们做到这一点: ```js const [a, b] = [1, 2, 3, 4, 5, 6]; -console.log(a, b); // 1, 2 +console.log(a, b); ``` -The variable `a` is assigned the first value of the array, and `b` is assigned the second value of the array. We can also access the value at any index in an array with destructuring by using commas to reach the desired index: +控制台将显示 `a` 和 `b` 的值为 `1, 2`。 + +数组的第一个值被赋值给变量 `a`,数组的第二个值被赋值给变量 `b`。 我们甚至能在数组解构中使用逗号分隔符,来获取任意一个想要的值: ```js const [a, b,,, c] = [1, 2, 3, 4, 5, 6]; -console.log(a, b, c); // 1, 2, 5 +console.log(a, b, c); ``` +控制台将显示 `a`、`b` 和 `c` 的值为 `1, 2, 5`。 + # --instructions-- -Use destructuring assignment to swap the values of `a` and `b` so that `a` receives the value stored in `b`, and `b` receives the value stored in `a`. +使用数组解构来交换变量 `a` 与 `b` 的值,使 `a` 接收 `b` 的值,而 `b` 接收 `a` 的值。 # --hints-- -Value of `a` should be 6, after swapping. +交换后,`a` 的值应该为 `6`。 ```js assert(a === 6); ``` -Value of `b` should be 8, after swapping. +交换后,`b` 的值应该为 `8`。 ```js assert(b === 8); ``` -You should use array destructuring to swap a and b. +应使用数组解构来交换 `a` 和 `b` 的值。 ```js assert(/\[\s*(\w)\s*,\s*(\w)\s*\]\s*=\s*\[\s*\2\s*,\s*\1\s*\]/g.test(code)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-nested-objects.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-nested-objects.md index 23f5ff9888..7c5f5bd338 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-nested-objects.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-nested-objects.md @@ -1,6 +1,6 @@ --- id: 587d7b89367417b2b2512b4a -title: Use Destructuring Assignment to Assign Variables from Nested Objects +title: 使用解构赋值从嵌套对象中分配变量 challengeType: 1 forumTopicId: 301214 dashedName: use-destructuring-assignment-to-assign-variables-from-nested-objects @@ -8,9 +8,9 @@ dashedName: use-destructuring-assignment-to-assign-variables-from-nested-objects # --description-- -You can use the same principles from the previous two lessons to destructure values from nested objects. +你可以使用前两节课程中相同的原则来解构嵌套对象中的值。 -Using an object similar to previous examples: +使用与前面的例子中类似的对象: ```js const user = { @@ -21,13 +21,13 @@ const user = { }; ``` -Here's how to extract the values of object properties and assign them to variables with the same name: +这是解构对象的属性值赋值给具有相同名字的变量: ```js const { johnDoe: { age, email }} = user; ``` -And here's how you can assign an object properties' values to variables with different names: +这是将对象的属性值赋值给具有不同名字的变量: ```js const { johnDoe: { age: userAge, email: userEmail }} = user; @@ -35,11 +35,11 @@ const { johnDoe: { age: userAge, email: userEmail }} = user; # --instructions-- -Replace the two assignments with an equivalent destructuring assignment. It should still assign the variables `lowToday` and `highToday` the values of `today.low` and `today.high` from the `LOCAL_FORECAST` object. +将两个赋值语句替换成等价的解构赋值。 `lowToday` 和 `highToday` 应该为 `LOCAL_FORECAST` 中 `today.low` 和 `today.high` 的值。 # --hints-- -You should remove the ES5 assignment syntax. +不能使用 ES5 的赋值语句。 ```js assert( @@ -48,7 +48,7 @@ assert( ); ``` -You should use destructuring to create the `lowToday` variable. +应该使用解构创建 `lowToday` 变量。 ```js assert( @@ -58,7 +58,7 @@ assert( ); ``` -You should use destructuring to create the `highToday` variable. +应该使用解构创建 `highToday` 变量。 ```js assert( @@ -68,7 +68,7 @@ assert( ); ``` -`lowToday` should be equal to `64` and `highToday` should be equal to `77`. +`lowToday` 应等于 `64`,`highToday` 应等于 `77`。 ```js assert(lowToday === 64 && highToday === 77); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-objects.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-objects.md index c0689cacb3..eb67e8b6ec 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-objects.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-objects.md @@ -1,6 +1,6 @@ --- id: 587d7b89367417b2b2512b49 -title: Use Destructuring Assignment to Assign Variables from Objects +title: 使用解构赋值从对象中分配变量 challengeType: 1 forumTopicId: 301215 dashedName: use-destructuring-assignment-to-assign-variables-from-objects @@ -8,30 +8,29 @@ dashedName: use-destructuring-assignment-to-assign-variables-from-objects # --description-- -Destructuring allows you to assign a new variable name when extracting values. You can do this by putting the new name after a colon when assigning the value. +可以给解构的值赋予一个新的变量名, 通过在赋值的时候将新的变量名放在冒号后面来实现。 -Using the same object from the last example: +还是以上个例子的对象来举例: ```js const user = { name: 'John Doe', age: 34 }; ``` -Here's how you can give new variable names in the assignment: +这是指定新的变量名的例子: ```js const { name: userName, age: userAge } = user; -// userName = 'John Doe', userAge = 34 ``` -You may read it as "get the value of `user.name` and assign it to a new variable named `userName`" and so on. +你可以这么理解这段代码:获取 `user.name` 的值,将它赋给一个新的变量 `userName`,等等。 `userName` 的值将是字符串 `John Doe`,`userAge` 的值将是数字 `34`。 # --instructions-- -Replace the two assignments with an equivalent destructuring assignment. It should still assign the variables `highToday` and `highTomorrow` the values of `today` and `tomorrow` from the `HIGH_TEMPERATURES` object. +使用解构赋值语句替换两个赋值语句。 将 `HIGH_TEMPERATURES` 的 `today` 和 `tomorrow` 的值赋值给 `highToday` 和 `highTomorrow`。 # --hints-- -You should remove the ES5 assignment syntax. +应该移除 ES5 赋值语句。 ```js assert( @@ -40,7 +39,7 @@ assert( ); ``` -You should use destructuring to create the `highToday` variable. +应该使用解构赋值语句创建 `highToday` 变量。 ```js assert( @@ -50,7 +49,7 @@ assert( ); ``` -You should use destructuring to create the `highTomorrow` variable. +应该使用解构赋值语句创建 `highTomorrow` 变量。 ```js assert( @@ -60,7 +59,7 @@ assert( ); ``` -`highToday` should be equal to `77` and `highTomorrow` should be equal to `80`. +`highToday` 应该等于 `77`,`highTomorrow` 应该等于 `80`。 ```js assert(highToday === 77 && highTomorrow === 80); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-extract-values-from-objects.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-extract-values-from-objects.md index ec873a1fa2..5b8ac905e5 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-extract-values-from-objects.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-extract-values-from-objects.md @@ -1,6 +1,6 @@ --- id: 5cfa550e84205a357704ccb6 -title: Use Destructuring Assignment to Extract Values from Objects +title: 使用解构赋值来获取对象的值 challengeType: 1 forumTopicId: 301216 dashedName: use-destructuring-assignment-to-extract-values-from-objects @@ -8,35 +8,38 @@ dashedName: use-destructuring-assignment-to-extract-values-from-objects # --description-- -Destructuring assignment is special syntax introduced in ES6, for neatly assigning values taken directly from an object. +解构赋值是 ES6 引入的新语法,用来从数组和对象中提取值,并优雅地对变量进行赋值。 -Consider the following ES5 code: +有如下 ES5 代码: ```js const user = { name: 'John Doe', age: 34 }; -const name = user.name; // name = 'John Doe' -const age = user.age; // age = 34 +const name = user.name; +const age = user.age; ``` -Here's an equivalent assignment statement using the ES6 destructuring syntax: +`name` 的值应该是字符串 `John Doe`, `age` 的值应该是数字 `34`。 + +下面是使用 ES6 解构赋值语句,实现相同效果: ```js const { name, age } = user; -// name = 'John Doe', age = 34 ``` -Here, the `name` and `age` variables will be created and assigned the values of their respective values from the `user` object. You can see how much cleaner this is. +同样,`name` 的值应该是字符串 `John Doe`, `age` 的值应该是数字 `34`。 -You can extract as many or few values from the object as you want. +在这里,自动创建 `name` 和 `age` 变量,并将 `user` 对象相应属性的值赋值给它们。 这个方法简洁多了。 + +你可以从对象中提取尽可能多或很少的值。 # --instructions-- -Replace the two assignments with an equivalent destructuring assignment. It should still assign the variables `today` and `tomorrow` the values of `today` and `tomorrow` from the `HIGH_TEMPERATURES` object. +把两个赋值语句替换成效果相同的解构赋值语句。 `today` 和 `tomorrow` 的值应该还是 `HIGH_TEMPERATURES` 对象中 `today` 和 `tomorrow` 属性的值。 # --hints-- -You should remove the ES5 assignment syntax. +应该移除 ES5 赋值语句。 ```js assert( @@ -46,7 +49,7 @@ assert( ); ``` -You should use destructuring to create the `today` variable. +应该使用解构赋值创建 `today` 变量。 ```js assert( @@ -58,7 +61,7 @@ assert( ); ``` -You should use destructuring to create the `tomorrow` variable. +应该使用解构赋值创建 `tomorrow` 变量。 ```js assert( @@ -70,7 +73,7 @@ assert( ); ``` -`today` should be equal to `77` and `tomorrow` should be equal to `80`. +`today` 应该等于 `77`,`tomorrow` 应该等于 `80`。 ```js assert(today === 77 && tomorrow === 80); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-pass-an-object-as-a-functions-parameters.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-pass-an-object-as-a-functions-parameters.md index b142b79a75..2b32c69e42 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-pass-an-object-as-a-functions-parameters.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-pass-an-object-as-a-functions-parameters.md @@ -1,6 +1,6 @@ --- id: 587d7b8a367417b2b2512b4d -title: Use Destructuring Assignment to Pass an Object as a Function's Parameters +title: 使用解构赋值将对象作为函数的参数传递 challengeType: 1 forumTopicId: 301217 dashedName: use-destructuring-assignment-to-pass-an-object-as-a-functions-parameters @@ -8,52 +8,52 @@ dashedName: use-destructuring-assignment-to-pass-an-object-as-a-functions-parame # --description-- -In some cases, you can destructure the object in a function argument itself. +在某些情况下,你可以在函数的参数里直接解构对象。 -Consider the code below: +请看以下代码: ```js const profileUpdate = (profileData) => { const { name, age, nationality, location } = profileData; - // do something with these variables + } ``` -This effectively destructures the object sent into the function. This can also be done in-place: +上面的操作解构了传给函数的对象。 这样的操作也可以直接在参数里完成: ```js const profileUpdate = ({ name, age, nationality, location }) => { - /* do something with these fields */ + } ``` -When `profileData` is passed to the above function, the values are destructured from the function parameter for use within the function. +当 `profileData` 被传递到上面的函数时,从函数参数中解构出值以在函数内使用。 # --instructions-- -Use destructuring assignment within the argument to the function `half` to send only `max` and `min` inside the function. +对 `half` 的参数进行解构赋值,仅将 `max` 与 `min` 的值传进函数。 # --hints-- -`stats` should be an `object`. +`stats` 的类型应该是一个 `object`。 ```js assert(typeof stats === 'object'); ``` -`half(stats)` should be `28.015` +`half(stats)` 应该等于 `28.015`。 ```js assert(half(stats) === 28.015); ``` -Destructuring should be used. +应该使用解构赋值。 ```js assert(__helpers.removeWhiteSpace(code).match(/half=\({\w+,\w+}\)/)); ``` -Destructured parameter should be used. +应该使用解构参数。 ```js assert(!code.match(/stats\.max|stats\.min/)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-with-the-rest-parameter-to-reassign-array-elements.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-with-the-rest-parameter-to-reassign-array-elements.md index 47b00256aa..5cb8814562 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-with-the-rest-parameter-to-reassign-array-elements.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-with-the-rest-parameter-to-reassign-array-elements.md @@ -1,7 +1,7 @@ --- id: 587d7b8a367417b2b2512b4c title: >- - Use Destructuring Assignment with the Rest Parameter to Reassign Array Elements + 使用解构赋值配合 rest 操作符来重新分配数组元素 challengeType: 1 forumTopicId: 301218 dashedName: >- @@ -10,43 +10,45 @@ dashedName: >- # --description-- -In some situations involving array destructuring, we might want to collect the rest of the elements into a separate array. +在解构数组的某些情况下,我们可能希望将剩下的元素放进另一个数组里面。 -The result is similar to `Array.prototype.slice()`, as shown below: +以下代码的结果与使用 `Array.prototype.slice()` 类似: ```js const [a, b, ...arr] = [1, 2, 3, 4, 5, 7]; -console.log(a, b); // 1, 2 -console.log(arr); // [3, 4, 5, 7] +console.log(a, b); +console.log(arr); ``` -Variables `a` and `b` take the first and second values from the array. After that, because of the rest parameter's presence, `arr` gets the rest of the values in the form of an array. The rest element only works correctly as the last variable in the list. As in, you cannot use the rest parameter to catch a subarray that leaves out the last element of the original array. +控制台将显示 `1, 2` 和 `[3, 4, 5, 7]`。 + +变量 `a` 和 `b` 分别接收数组的第一个和第二个值。 之后,因为 rest 操作符的存在,`arr` 获取了原数组剩余的元素的值。 rest 操作符只能对数组列表最后的元素起作用。 这意味着你不能使用 rest 操作符来截取原数组中间的元素作为子数组。 # --instructions-- -Use destructuring assignment with the rest parameter to perform an effective `Array.prototype.slice()` so that `arr` is a sub-array of the original array `source` with the first two elements omitted. +使用解构赋值以及 rest 操作符来进行和 `Array.prototype.slice()` 相同的操作,使 `arr` 是原数组 `source` 除开前两个元素的子数组。 # --hints-- -`arr` should be `[3,4,5,6,7,8,9,10]` +`arr` 应该是 `[3,4,5,6,7,8,9,10]`。 ```js assert(arr.every((v, i) => v === i + 3) && arr.length === 8); ``` -`source` should be `[1,2,3,4,5,6,7,8,9,10]` +`source` 应该是 `[1,2,3,4,5,6,7,8,9,10]`。 ```js assert(source.every((v, i) => v === i + 1) && source.length === 10); ``` -`Array.slice()` should not be used. +不应该使用 `Array.slice()`。 ```js (getUserInput) => assert(!getUserInput('index').match(/slice/g)); ``` -Destructuring on `list` should be used. +应该对 `list` 进行解构赋值。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-export-to-share-a-code-block.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-export-to-share-a-code-block.md index cffcbbe642..17fdb5c057 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-export-to-share-a-code-block.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-export-to-share-a-code-block.md @@ -1,6 +1,6 @@ --- id: 587d7b8c367417b2b2512b56 -title: Use export to Share a Code Block +title: 用 export 来重用代码块 challengeType: 1 forumTopicId: 301219 dashedName: use-export-to-share-a-code-block @@ -8,7 +8,7 @@ dashedName: use-export-to-share-a-code-block # --description-- -Imagine a file called `math_functions.js` that contains several functions related to mathematical operations. One of them is stored in a variable, `add`, that takes in two numbers and returns their sum. You want to use this function in several different JavaScript files. In order to share it with these other files, you first need to `export` it. +假设有一个文件 `math_functions.js`,该文件包含了数学运算相关的一些函数。 其中一个存储在变量 `add` 里,该函数接受两个数字作为参数返回它们的和。 你想在几个不同的 JavaScript 文件中使用这个函数。 要实现这个目的,就需要 `export` 它。 ```js export const add = (x, y) => { @@ -16,7 +16,7 @@ export const add = (x, y) => { } ``` -The above is a common way to export a single function, but you can achieve the same thing like this: +上面是导出单个函数常用方法,还可以这样导出: ```js const add = (x, y) => { @@ -26,7 +26,7 @@ const add = (x, y) => { export { add }; ``` -When you export a variable or function, you can import it in another file and use it without having to rewrite the code. You can export multiple things by repeating the first example for each thing you want to export, or by placing them all in the export statement of the second example, like this: +导出变量和函数后,就可以在其它文件里导入使用从而避免了代码冗余。 重复第一个例子的代码可以导出多个对象或函数,在第二个例子里面的导出语句中添加更多值也可以导出多项,例子如下: ```js export { add, subtract }; @@ -34,11 +34,11 @@ export { add, subtract }; # --instructions-- -There are two string-related functions in the editor. Export both of them using the method of your choice. +编辑框中有两个字符串相关的函数。 选用一种方法导出两个函数。 # --hints-- -You should properly export `uppercaseString`. +应该导出 `uppercaseString` 变量。 ```js assert( @@ -48,7 +48,7 @@ assert( ); ``` -You should properly export `lowercaseString`. +应该导出 `lowercaseString` 变量。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object.md index 04e7ec825a..b5b965af46 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object.md @@ -1,6 +1,6 @@ --- id: 587d7b8c367417b2b2512b54 -title: Use getters and setters to Control Access to an Object +title: 使用 getter 和 setter 来控制对象的访问 challengeType: 1 forumTopicId: 301220 dashedName: use-getters-and-setters-to-control-access-to-an-object @@ -8,13 +8,13 @@ dashedName: use-getters-and-setters-to-control-access-to-an-object # --description-- -You can obtain values from an object and set the value of a property within an object. +你可以从对象中获得一个值,也可以给对象的属性赋值。 -These are classically called getters and setters. +这些操作通常被称为 getters 以及 setters。 -Getter functions are meant to simply return (get) the value of an object's private variable to the user without the user directly accessing the private variable. +Getter 函数的作用是可以让对象返回一个私有变量,而不需要直接去访问私有变量。 -Setter functions are meant to modify (set) the value of an object's private variable based on the value passed into the setter function. This change could involve calculations, or even overwriting the previous value completely. +Setter 函数的作用是可以基于传进的参数来修改对象中私有变量。 这些修改可以是计算,或者是直接替换之前的值。 ```js class Book { @@ -31,30 +31,34 @@ class Book { } } const novel = new Book('anonymous'); -console.log(novel.writer); // anonymous +console.log(novel.writer); novel.writer = 'newAuthor'; -console.log(novel.writer); // newAuthor +console.log(novel.writer); ``` -Notice the syntax used to invoke the getter and setter. They do not even look like functions. Getters and setters are important because they hide internal implementation details. **Note:** It is convention to precede the name of a private variable with an underscore (`_`). However, the practice itself does not make a variable private. +控制台将显示字符串 `anonymous` 和 `newAuthor`。 + +请注意用于调用 getter 和 setter 的语法。 它们甚至看起来不像是函数。 getter 和 setter 非常重要,因为它们隐藏了内部的实现细节。 + +**注意:**通常会在私有变量前添加下划线(`_`)。 然而,这种做法本身并不是将变量变成私有的。 # --instructions-- -Use the `class` keyword to create a Thermostat class. The constructor accepts a Fahrenheit temperature. +使用 `class` 关键字创建一个 `Thermostat` class。 `constructor` 接收一个华氏温度。 -In the class, create a `getter` to obtain the temperature in Celsius and a `setter` to set the temperature in Celsius. +在 class 中,创建一个 `getter` 来获取摄氏温度和一个 `setter` 来设置温度值。 -Remember that `C = 5/9 * (F - 32)` and `F = C * 9.0 / 5 + 32`, where `F` is the value of temperature in Fahrenheit, and `C` is the value of the same temperature in Celsius. +记得在 `C = 5/9 * (F - 32)` 和 `F = C * 9.0 / 5 + 32` 中,`F` 是华氏温度值,`C` 是摄氏温度值。 -**Note:** When you implement this, you will track the temperature inside the class in one scale, either Fahrenheit or Celsius. +**注意:**完成这个挑战后,应该在 class 中使用一个温度标准,要么是华氏温度,要么是摄氏温度。 -This is the power of a getter and a setter. You are creating an API for another user, who can get the correct result regardless of which one you track. +这就是 getter 和 setter 的功能。 你正在为别的用户创建一个 API,不论你使用哪一个,用户都将获得正确的结果。 -In other words, you are abstracting implementation details from the user. +或者说,你从用户需求中抽象出了实现细节。 # --hints-- -`Thermostat` should be a `class` with a defined `constructor` method. +`Thermostat` 应该是一个具有 `constructor` 方法的 `class`。 ```js assert( @@ -63,13 +67,13 @@ assert( ); ``` -`class` keyword should be used. +应该使用 `class` 关键词。 ```js assert(code.match(/class/g)); ``` -`Thermostat` should be able to be instantiated. +`Thermostat` 应该可以被实例化。 ```js assert( @@ -80,7 +84,7 @@ assert( ); ``` -When instantiated with a Fahrenheit value, `Thermostat` should set the correct temperature. +当实例化华氏温度值时,`Thermostat` 应该被设置为正确的 `temperature`。 ```js assert( @@ -91,7 +95,7 @@ assert( ); ``` -A `getter` should be defined. +应该定义一个 `getter`。 ```js assert( @@ -105,7 +109,7 @@ assert( ); ``` -A `setter` should be defined. +应该定义一个 `setter`。 ```js assert( @@ -119,7 +123,7 @@ assert( ); ``` -Calling the `setter` with a Celsius value should set the temperature. +调用带有摄氏温度值的 `setter` 应该设置 `temperature`。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-the-rest-parameter-with-function-parameters.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-the-rest-parameter-with-function-parameters.md index 888e68da6b..60f7d5280b 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-the-rest-parameter-with-function-parameters.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-the-rest-parameter-with-function-parameters.md @@ -1,6 +1,6 @@ --- id: 587d7b88367417b2b2512b47 -title: Use the Rest Parameter with Function Parameters +title: 将 rest 操作符与函数参数一起使用 challengeType: 1 forumTopicId: 301221 dashedName: use-the-rest-parameter-with-function-parameters @@ -8,51 +8,53 @@ dashedName: use-the-rest-parameter-with-function-parameters # --description-- -In order to help us create more flexible functions, ES6 introduces the rest parameter for function parameters. With the rest parameter, you can create functions that take a variable number of arguments. These arguments are stored in an array that can be accessed later from inside the function. +ES6 推出了用于函数参数的 rest 操作符帮助我们创建更加灵活的函数。 rest 操作符可以用于创建有一个变量来接受多个参数的函数。 这些参数被储存在一个可以在函数内部读取的数组中。 -Check out this code: +请看以下代码: ```js function howMany(...args) { return "You have passed " + args.length + " arguments."; } -console.log(howMany(0, 1, 2)); // You have passed 3 arguments. -console.log(howMany("string", null, [1, 2, 3], { })); // You have passed 4 arguments. +console.log(howMany(0, 1, 2)); +console.log(howMany("string", null, [1, 2, 3], { })); ``` -The rest parameter eliminates the need to check the `args` array and allows us to apply `map()`, `filter()` and `reduce()` on the parameters array. +控制台将显示字符串 `You have passed 3 arguments.` 和 `You have passed 4 arguments.`。 + +使用 rest 参数,就不需要查看 `args` 数组,并且允许我们在参数数组上使用 `map()`、`filter()` 和 `reduce()`。 # --instructions-- -Modify the function `sum` using the rest parameter in such a way that the function `sum` is able to take any number of arguments and return their sum. +修改 `sum` 函数,使用 rest 参数,使 `sum` 函数可以接收任意数量的参数,并返回它们的总和。 # --hints-- -The result of `sum(0,1,2)` should be 3 +`sum(0,1,2)` 的结果应是 3。 ```js assert(sum(0, 1, 2) === 3); ``` -The result of `sum(1,2,3,4)` should be 10 +`sum(1,2,3,4)` 的结果应是 10。 ```js assert(sum(1, 2, 3, 4) === 10); ``` -The result of `sum(5)` should be 5 +`sum(5)` 的结果应是 5。 ```js assert(sum(5) === 5); ``` -The result of `sum()` should be 0 +`sum()` 的结果应是 0。 ```js assert(sum() === 0); ``` -`sum` should be an arrow function which uses the rest parameter syntax (`...`) on the `args` parameter. +`sum` 应是一个箭头函数,对 `args` 参数使用 rest 操作符语法(`...`)。 ```js assert(__helpers.removeWhiteSpace(code).match(/sum=\(\.\.\.args\)=>/)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-the-spread-operator-to-evaluate-arrays-in-place.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-the-spread-operator-to-evaluate-arrays-in-place.md index 9fa3b6b1b5..5412467732 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-the-spread-operator-to-evaluate-arrays-in-place.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-the-spread-operator-to-evaluate-arrays-in-place.md @@ -1,6 +1,6 @@ --- id: 587d7b89367417b2b2512b48 -title: Use the Spread Operator to Evaluate Arrays In-Place +title: 使用 spread 运算符展开数组项 challengeType: 1 forumTopicId: 301222 dashedName: use-the-spread-operator-to-evaluate-arrays-in-place @@ -8,47 +8,51 @@ dashedName: use-the-spread-operator-to-evaluate-arrays-in-place # --description-- -ES6 introduces the spread operator, which allows us to expand arrays and other expressions in places where multiple parameters or elements are expected. +ES6 引入了展开操作符,可以展开数组以及需要多个参数或元素的表达式。 -The ES5 code below uses `apply()` to compute the maximum value in an array: +下面的 ES5 代码使用了 `apply()` 来计算数组的最大值: ```js var arr = [6, 89, 3, 45]; -var maximus = Math.max.apply(null, arr); // returns 89 +var maximus = Math.max.apply(null, arr); ``` -We had to use `Math.max.apply(null, arr)` because `Math.max(arr)` returns `NaN`. `Math.max()` expects comma-separated arguments, but not an array. The spread operator makes this syntax much better to read and maintain. +`maximus` 的值为 `89`。 + +我们必须使用 `Math.max.apply(null, arr)`,因为 `Math.max(arr)` 返回 `NaN`。 `Math.max()` 函数中需要传入的是一系列由逗号分隔的参数,而不是一个数组。 展开操作符可以提升代码的可读性,使代码易于维护。 ```js const arr = [6, 89, 3, 45]; -const maximus = Math.max(...arr); // returns 89 +const maximus = Math.max(...arr); ``` -`...arr` returns an unpacked array. In other words, it *spreads* the array. However, the spread operator only works in-place, like in an argument to a function or in an array literal. The following code will not work: +`maximus` 的值应该是 `89`。 + +`...arr` 返回一个解压的数组。 也就是说,它*展开*数组。 然而,展开操作符只能够在函数的参数中或者数组中使用。 下面的代码将会报错: ```js -const spreaded = ...arr; // will throw a syntax error +const spreaded = ...arr; ``` # --instructions-- -Copy all contents of `arr1` into another array `arr2` using the spread operator. +使用展开操作符将 `arr1` 中的内容都复制到 `arr2` 中去。 # --hints-- -`arr2` should be correct copy of `arr1`. +`arr2` 应该是从 `arr1` 复制而来。 ```js assert(arr2.every((v, i) => v === arr1[i]) && arr2.length); ``` -`...` spread operator should be used to duplicate `arr1`. +应使用展开操作符 `...` 来复制 `arr1`。 ```js assert(code.match(/Array\(\s*\.\.\.arr1\s*\)|\[\s*\.\.\.arr1\s*\]/)); ``` -`arr2` should remain unchanged when `arr1` is changed. +当 `arr1` 改变的时候,`arr2` 应保持不变。 ```js assert((arr1, arr2) => { diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/write-arrow-functions-with-parameters.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/write-arrow-functions-with-parameters.md index 390cb0933c..f16e49c024 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/write-arrow-functions-with-parameters.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/write-arrow-functions-with-parameters.md @@ -1,6 +1,6 @@ --- id: 587d7b88367417b2b2512b44 -title: Write Arrow Functions with Parameters +title: 编写带参数的箭头函数 challengeType: 1 forumTopicId: 301223 dashedName: write-arrow-functions-with-parameters @@ -8,48 +8,49 @@ dashedName: write-arrow-functions-with-parameters # --description-- -Just like a regular function, you can pass arguments into an arrow function. +和一般的函数一样,你也可以给箭头函数传递参数。 ```js -// doubles input value and returns it const doubler = (item) => item * 2; -doubler(4); // returns 8 +doubler(4); ``` -If an arrow function has a single parameter, the parentheses enclosing the parameter may be omitted. +`doubler(4)` 将返回 `8`。 + +如果箭头函数只有一个参数,则可以省略参数外面的括号。 ```js -// the same function, without the parameter parentheses const doubler = item => item * 2; ``` -It is possible to pass more than one argument into an arrow function. +可以给箭头函数传递多个参数。 ```js -// multiplies the first input value by the second and returns it const multiplier = (item, multi) => item * multi; -multiplier(4, 2); // returns 8 +multiplier(4, 2); ``` +`multiplier(4, 2)` 将返回 `8`。 + # --instructions-- -Rewrite the `myConcat` function which appends contents of `arr2` to `arr1` so that the function uses arrow function syntax. +使用箭头函数的语法重写 `myConcat` 函数,将 `arr2` 的内容添加到 `arr1`。 # --hints-- -You should replace the `var` keyword. +应替换 `var` 关键词。 ```js (getUserInput) => assert(!getUserInput('index').match(/var/g)); ``` -`myConcat` should be a constant variable (by using `const`). +`myConcat` 应该是一个常量(使用`const`)。 ```js (getUserInput) => assert(getUserInput('index').match(/const\s+myConcat/g)); ``` -`myConcat` should be an arrow function with two parameters +`myConcat` 应该是一个带有两个参数的箭头函数。 ```js assert( @@ -58,13 +59,13 @@ assert( ); ``` -`myConcat()` should return `[1, 2, 3, 4, 5]`. +`myConcat()` 应该返回 `[1, 2, 3, 4, 5]`。 ```js assert.deepEqual(myConcat([1, 2], [3, 4, 5]), [1, 2, 3, 4, 5]); ``` -`function` keyword should not be used. +不能使用 `function` 关键字。 ```js (getUserInput) => assert(!getUserInput('index').match(/function/g)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/write-concise-declarative-functions-with-es6.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/write-concise-declarative-functions-with-es6.md index b7bd2904d8..384c805217 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/write-concise-declarative-functions-with-es6.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/write-concise-declarative-functions-with-es6.md @@ -1,6 +1,6 @@ --- id: 587d7b8b367417b2b2512b50 -title: Write Concise Declarative Functions with ES6 +title: 用 ES6 编写简洁的函数声明 challengeType: 1 forumTopicId: 301224 dashedName: write-concise-declarative-functions-with-es6 @@ -8,7 +8,7 @@ dashedName: write-concise-declarative-functions-with-es6 # --description-- -When defining functions within objects in ES5, we have to use the keyword `function` as follows: +在 ES5 中,当我们需要在对象中定义一个函数的时候,必须像这样使用 `function` 关键字: ```js const person = { @@ -19,7 +19,7 @@ const person = { }; ``` -With ES6, You can remove the `function` keyword and colon altogether when defining functions in objects. Here's an example of this syntax: +用 ES6 的语法在对象中定义函数的时候,可以删除 `function` 关键词和冒号。 请看以下例子: ```js const person = { @@ -32,17 +32,17 @@ const person = { # --instructions-- -Refactor the function `setGear` inside the object `bicycle` to use the shorthand syntax described above. +使用以上这种简短的语法,重构在 `bicycle` 对象中的 `setGear` 函数。 # --hints-- -Traditional function expression should not be used. +不应使用传统的函数定义方法。 ```js (getUserInput) => assert(!__helpers.removeJSComments(code).match(/function/)); ``` -`setGear` should be a declarative function. +`setGear` 应是一个声明函数。 ```js assert( @@ -50,7 +50,7 @@ assert( ); ``` -`bicycle.setGear(48)` should change the `gear` value to 48. +`bicycle.setGear(48)` 应将 `gear` 的值改为 48。 ```js assert(new bicycle.setGear(48).gear === 48); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/write-concise-object-literal-declarations-using-object-property-shorthand.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/write-concise-object-literal-declarations-using-object-property-shorthand.md index 33dabc5d3a..6f5f00d828 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/write-concise-object-literal-declarations-using-object-property-shorthand.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/write-concise-object-literal-declarations-using-object-property-shorthand.md @@ -1,6 +1,6 @@ --- id: 587d7b8a367417b2b2512b4f -title: Write Concise Object Literal Declarations Using Object Property Shorthand +title: 使用简单字段编写简洁的对象字面量声明 challengeType: 1 forumTopicId: 301225 dashedName: write-concise-object-literal-declarations-using-object-property-shorthand @@ -8,9 +8,9 @@ dashedName: write-concise-object-literal-declarations-using-object-property-shor # --description-- -ES6 adds some nice support for easily defining object literals. +ES6 添加了一些很棒的功能,用于更方便地定义对象。 -Consider the following code: +请看以下代码: ```js const getMousePosition = (x, y) => ({ @@ -19,7 +19,7 @@ const getMousePosition = (x, y) => ({ }); ``` -`getMousePosition` is a simple function that returns an object containing two properties. ES6 provides the syntactic sugar to eliminate the redundancy of having to write `x: x`. You can simply write `x` once, and it will be converted to`x: x` (or something equivalent) under the hood. Here is the same function from above rewritten to use this new syntax: +`getMousePosition` 简单的函数,返回拥有两个属性的对象。 ES6 提供了一个语法糖,消除了类似 `x: x` 这种冗余的写法。 你可以只写一次 `x`,解释器会自动将其转换成 `x: x`(或效果相同的内容)。 下面是使用这种语法重写的同样的函数: ```js const getMousePosition = (x, y) => ({ x, y }); @@ -27,11 +27,11 @@ const getMousePosition = (x, y) => ({ x, y }); # --instructions-- -Use object property shorthand with object literals to create and return an object with `name`, `age` and `gender` properties. +请使用简单属性对象的语法来创建并返回一个具有 `name`、`age` 和 `gender` 属性的对象。 # --hints-- -`createPerson("Zodiac Hasbro", 56, "male")` should return `{name: "Zodiac Hasbro", age: 56, gender: "male"}`. +`createPerson("Zodiac Hasbro", 56, "male")` 应该返回 `{name: "Zodiac Hasbro", age: 56, gender: "male"}`。 ```js assert.deepEqual( @@ -40,7 +40,7 @@ assert.deepEqual( ); ``` -Your code should not use `key:value`. +不要使用 `key:value`。 ```js (getUserInput) => assert(!getUserInput('index').match(/:/g)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/avoid-mutations-and-side-effects-using-functional-programming.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/avoid-mutations-and-side-effects-using-functional-programming.md index 0f401beeab..deeeb4d8ea 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/avoid-mutations-and-side-effects-using-functional-programming.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/avoid-mutations-and-side-effects-using-functional-programming.md @@ -1,6 +1,6 @@ --- id: 587d7b8e367417b2b2512b5e -title: Avoid Mutations and Side Effects Using Functional Programming +title: 使用函数式编程避免变化和副作用 challengeType: 1 forumTopicId: 301228 dashedName: avoid-mutations-and-side-effects-using-functional-programming @@ -8,39 +8,39 @@ dashedName: avoid-mutations-and-side-effects-using-functional-programming # --description-- -If you haven't already figured it out, the issue in the previous challenge was with the `splice` call in the `tabClose()` function. Unfortunately, `splice` changes the original array it is called on, so the second call to it used a modified array, and gave unexpected results. +如果你还没想通,上一个挑战的问题出在 `tabClose()` 函数里的 `splice`。 不幸的是,`splice` 修改了调用它的原始数组,所以第二次调用它时是基于修改后的数组,才给出了意料之外的结果。 -This is a small example of a much larger pattern - you call a function on a variable, array, or an object, and the function changes the variable or something in the object. +这是一个小例子,还有更广义的定义——在变量,数组或对象上调用一个函数,这个函数会改变对象中的变量或其他东西。 -One of the core principles of functional programming is to not change things. Changes lead to bugs. It's easier to prevent bugs knowing that your functions don't change anything, including the function arguments or any global variable. +函数式编程的核心原则之一是不改变任何东西。 变化会导致错误。 如果一个函数不改变传入的参数、全局变量等数据,那么它造成问题的可能性就会小很多。 -The previous example didn't have any complicated operations but the `splice` method changed the original array, and resulted in a bug. +前面的例子没有任何复杂的操作,但是 `splice` 方法改变了原始数组,导致 bug 产生。 -Recall that in functional programming, changing or altering things is called mutation, and the outcome is called a side effect. A function, ideally, should be a pure function, meaning that it does not cause any side effects. +回想一下,在函数式编程中,改变或变更叫做 mutation,这种改变的结果叫做“副作用”(side effect)。 理想情况下,函数应该是不会产生任何副作用的 pure function。 -Let's try to master this discipline and not alter any variable or object in our code. +让我们尝试掌握这个原则:不要改变代码中的任何变量或对象。 # --instructions-- -Fill in the code for the function `incrementer` so it returns the value of the global variable `fixedValue` increased by one. +填写 `incrementer` 函数的代码,使其返回值为全局变量 `fixedValue` 增加 1 。 # --hints-- -Your function `incrementer` should not change the value of `fixedValue` (which is `4`). +`incrementer` 函数不能改变 `fixedValue` 的值(`4`)。 ```js incrementer(); assert(fixedValue === 4); ``` -Your `incrementer` function should return a value that is one larger than the `fixedValue` value. +`incrementer` 函数应返回比 `fixedValue` 变量更大的值。 ```js const __newValue = incrementer(); assert(__newValue === 5); ``` -Your `incrementer` function should return a value based on the global `fixedValue` variable value. +你的 `incrementer` 函数返回的值应该基于全局变量 `fixedValue` 的值。 ```js (function () { diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype.md index b1098b2b28..03bc973991 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype.md @@ -1,6 +1,6 @@ --- id: 587d7b8f367417b2b2512b62 -title: Implement map on a Prototype +title: 在原型上实现 map 方法 challengeType: 1 forumTopicId: 301230 dashedName: implement-map-on-a-prototype @@ -8,25 +8,25 @@ dashedName: implement-map-on-a-prototype # --description-- -As you have seen from applying `Array.prototype.map()`, or simply `map()` earlier, the `map` method returns an array of the same length as the one it was called on. It also doesn't alter the original array, as long as its callback function doesn't. +之前用到了 `Array.prototype.map()` 方法(即 `map()`),通过 `map` 返回一个与调用它的数组长度相同的数组。 只要它的回调函数不改变原始数组,它就不会改变原始数组。 -In other words, `map` is a pure function, and its output depends solely on its inputs. Plus, it takes another function as its argument. +换句话说,`map` 是一个纯函数,它的输出仅取决于输入的数组和作为参数传入的回调函数。 此外,它接收另一个函数作为它的参数。 -You might learn a lot about the `map` method if you implement your own version of it. It is recommended you use a `for` loop or `Array.prototype.forEach()`. +实现一个 `map`,加深对它的了解。 你可以用 `for` 循环或者 `Array.prototype.forEach()` 方法。 # --instructions-- -Write your own `Array.prototype.myMap()`, which should behave exactly like `Array.prototype.map()`. You should not use the built-in `map` method. The `Array` instance can be accessed in the `myMap` method using `this`. +写一个和 `Array.prototype.map()` 一样的 `Array.prototype.myMap()`。 不能使用内置的 `map` 方法。 在 `myMap` 方法内,可以使用 `this` 访问 `Array` 实例。 # --hints-- -`new_s` should equal `[46, 130, 196, 10]`. +`new_s` 应该等于 `[46, 130, 196, 10]`。 ```js assert(JSON.stringify(new_s) === JSON.stringify([46, 130, 196, 10])); ``` -Your code should not use the `map` method. +不能使用 `map` 方法。 ```js assert(!code.match(/\.?[\s\S]*?map/g)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/implement-the-filter-method-on-a-prototype.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/implement-the-filter-method-on-a-prototype.md index a9469de977..08c03f10d0 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/implement-the-filter-method-on-a-prototype.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/implement-the-filter-method-on-a-prototype.md @@ -1,6 +1,6 @@ --- id: 587d7b8f367417b2b2512b64 -title: Implement the filter Method on a Prototype +title: 在原型上实现 filter 方法 challengeType: 1 forumTopicId: 301231 dashedName: implement-the-filter-method-on-a-prototype @@ -8,21 +8,21 @@ dashedName: implement-the-filter-method-on-a-prototype # --description-- -You might learn a lot about the `filter` method if you implement your own version of it. It is recommended you use a `for` loop or `Array.prototype.forEach()`. +为了加深对 `filter` 的理解,可以自己实现一个。 可以用 `for` 循环或 `Array.prototype.forEach()`。 # --instructions-- -Write your own `Array.prototype.myFilter()`, which should behave exactly like `Array.prototype.filter()`. You should not use the built-in `filter` method. The `Array` instance can be accessed in the `myFilter` method using `this`. +编写一个和 `Array.prototype.filter()` 功能一样的 `Array.prototype.myFilter()` 方法。 不能使用内置的 `filter` 方法。 在 `myFilter` 方法内部,可以使用 `this` 访问 `Array` 实例。 # --hints-- -`new_s` should equal `[23, 65, 5]`. +`new_s` 应该等于 `[23, 65, 5]`。 ```js assert(JSON.stringify(new_s) === JSON.stringify([23, 65, 5])); ``` -Your code should not use the `filter` method. +不应该使用 `filter` 方法。 ```js assert(!code.match(/\.?[\s\S]*?filter/g)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/introduction-to-currying-and-partial-application.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/introduction-to-currying-and-partial-application.md index 1d3651620f..de39dc5653 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/introduction-to-currying-and-partial-application.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/introduction-to-currying-and-partial-application.md @@ -1,6 +1,6 @@ --- id: 587d7dab367417b2b2512b70 -title: Introduction to Currying and Partial Application +title: 函数柯里化 challengeType: 1 forumTopicId: 301232 dashedName: introduction-to-currying-and-partial-application @@ -8,74 +8,72 @@ dashedName: introduction-to-currying-and-partial-application # --description-- -The arity of a function is the number of arguments it requires. Currying a function means to convert a function of N arity into N functions of arity 1. +arity 是函数所需的形参的数量。 函数柯里化(Currying)意思是把接受多个 arity 的函数变换成接受单一arity 的函数。 -In other words, it restructures a function so it takes one argument, then returns another function that takes the next argument, and so on. +换句话说,就是重构函数让它接收一个参数,然后返回接收下一个参数的函数,依此类推。 -Here's an example: +举个例子: ```js -//Un-curried function function unCurried(x, y) { return x + y; } -//Curried function function curried(x) { return function(y) { return x + y; } } -//Alternative using ES6 + const curried = x => y => x + y -curried(1)(2) // Returns 3 +curried(1)(2) ``` -This is useful in your program if you can't supply all the arguments to a function at one time. You can save each function call into a variable, which will hold the returned function reference that takes the next argument when it's available. Here's an example using the curried function in the example above: +`curried(1)(2)` 会返回 `3`。 + +柯里化在不能一次为函数提供所有参数情况下很有用。 因为它可以将每个函数的调用保存到一个变量中,该变量将保存返回的函数引用,该引用在下一个参数可用时接受该参数。 下面是使用柯里化函数的例子: ```js -// Call a curried function in parts: var funcForY = curried(1); -console.log(funcForY(2)); // Prints 3 +console.log(funcForY(2)); // 3 ``` -Similarly, partial application can be described as applying a few arguments to a function at a time and returning another function that is applied to more arguments. Here's an example: +类似地,局部调用( partial application)的意思是一次对一个函数应用几个参数,然后返回另一个应用更多参数的函数。 这是一个示例: ```js -//Impartial function function impartial(x, y, z) { return x + y + z; } var partialFn = impartial.bind(this, 1, 2); -partialFn(10); // Returns 13 +partialFn(10); // 13 ``` # --instructions-- -Fill in the body of the `add` function so it uses currying to add parameters `x`, `y`, and `z`. +填写 `add` 函数主体部分,用柯里化添加参数 `x`,`y` 和 `z`. # --hints-- -`add(10)(20)(30)` should return `60`. +`add(10)(20)(30)` 应返回 `60`。 ```js assert(add(10)(20)(30) === 60); ``` -`add(1)(2)(3)` should return `6`. +`add(1)(2)(3)` 应返回 `6`。 ```js assert(add(1)(2)(3) === 6); ``` -`add(11)(22)(33)` should return `66`. +`add(11)(22)(33)` 应返回 `66`。 ```js assert(add(11)(22)(33) === 66); ``` -Your code should include a final statement that returns `x + y + z`. +应返回 `x + y + z` 的最终结果。 ```js assert(code.match(/[xyz]\s*?\+\s*?[xyz]\s*?\+\s*?[xyz]/g)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/learn-about-functional-programming.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/learn-about-functional-programming.md index a0cc4d99a3..492c8e6041 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/learn-about-functional-programming.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/learn-about-functional-programming.md @@ -1,6 +1,6 @@ --- id: 587d7b8d367417b2b2512b5b -title: Learn About Functional Programming +title: 学习函数式编程 challengeType: 1 forumTopicId: 301233 dashedName: learn-about-functional-programming @@ -8,33 +8,33 @@ dashedName: learn-about-functional-programming # --description-- -Functional programming is a style of programming where solutions are simple, isolated functions, without any side effects outside of the function scope. +函数式编程是一种方案简单、功能独立、对作用域外没有任何副作用的编程范式。 `INPUT -> PROCESS -> OUTPUT` -Functional programming is about: +函数式编程: -1) Isolated functions - there is no dependence on the state of the program, which includes global variables that are subject to change +1)功能独立——不依赖于程序的状态(比如可能发生变化的全局变量); -2) Pure functions - the same input always gives the same output +2)纯函数——同一个输入永远能得到同一个输出; -3) Functions with limited side effects - any changes, or mutations, to the state of the program outside the function are carefully controlled +3)有限的副作用——可以严格地限制函数外部对状态的更改。 # --instructions-- -The members of freeCodeCamp happen to love tea. +freeCodeCamp 成员在 love tea 的故事。 -In the code editor, the `prepareTea` and `getTea` functions are already defined for you. Call the `getTea` function to get 40 cups of tea for the team, and store them in the `tea4TeamFCC` variable. +在代码编辑器中,已经为你定义好了 `prepareTea` 和 `getTea` 函数。 调用 `getTea` 函数为团队准备 40 杯茶,并将它们存储在 `tea4TeamFCC` 变量里。 # --hints-- -The `tea4TeamFCC` variable should hold 40 cups of tea for the team. +`tea4TeamFCC` 变量里应有 40 杯为团队准备的茶。 ```js assert(tea4TeamFCC.length === 40); ``` -The `tea4TeamFCC` variable should hold cups of green tea. +`tea4TeamFCC` 变量里应有 greenTea。 ```js assert(tea4TeamFCC[0] === 'greenTea'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/refactor-global-variables-out-of-functions.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/refactor-global-variables-out-of-functions.md index 0eea537b77..c756cb96f2 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/refactor-global-variables-out-of-functions.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/refactor-global-variables-out-of-functions.md @@ -1,6 +1,6 @@ --- id: 587d7b8f367417b2b2512b60 -title: Refactor Global Variables Out of Functions +title: 在函数中重构全局变量 challengeType: 1 forumTopicId: 301235 dashedName: refactor-global-variables-out-of-functions @@ -8,23 +8,23 @@ dashedName: refactor-global-variables-out-of-functions # --description-- -So far, we have seen two distinct principles for functional programming: +目前为止,我们已经看到了函数式编程的两个原则: -1) Don't alter a variable or object - create new variables and objects and return them if need be from a function. Hint: using something like `var newArr = arrVar`, where `arrVar` is an array will simply create a reference to the existing variable and not a copy. So changing a value in `newArr` would change the value in `arrVar`. +1) 不要更改变量或对象 - 创建新变量和对象,并在需要时从函数返回它们。 提示:使用类似 `var newArr = arrVar` 时 `arrVar` 是一个数组,代码只是创建一个对现有变量的引用,而不是副本。 所以更改 `newArr` 中的值会同时更改 `arrVar` 中的值。 -2) Declare function parameters - any computation inside a function depends only on the arguments passed to the function, and not on any global object or variable. +2) 声明函数参数 - 函数内的任何计算仅取决于参数,而不取决于任何全局对象或变量。 -Adding one to a number is not very exciting, but we can apply these principles when working with arrays or more complex objects. +给数字增加 1 不够刺激,我们可以在处理数组或更复杂的对象时应用这些原则。 # --instructions-- -Rewrite the code so the global array `bookList` is not changed inside either function. The `add` function should add the given `bookName` to the end of the array passed to it and return a new array (list). The `remove` function should remove the given `bookName` from the array passed to it. +重构代码,使全局数组 `bookList` 在函数内部不会被改变。 `add` 函数可以将指定的 `bookName` 增加到数组末尾并返回一个新的数组(列表)。 `remove` 函数可以从数组中移除指定 `bookName`。 -**Note:** Both functions should return an array, and any new parameters should be added before the `bookName` parameter. +**注意:** 两个函数都应该返回一个数组,任何新参数都应该在 `bookName` 参数之前添加。 # --hints-- -`bookList` should not change and still equal `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`. +`bookList` 应等于 `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`. ```js assert( @@ -38,7 +38,7 @@ assert( ); ``` -`newBookList` should equal `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]`. +`newBookList` 应等于 `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]`. ```js assert( @@ -53,7 +53,7 @@ assert( ); ``` -`newerBookList` should equal `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`. +`newerBookList` 应等于 `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`. ```js assert( @@ -66,7 +66,7 @@ assert( ); ``` -`newestBookList` should equal `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]`. +`newestBookList` 应等于 `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]`. ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/remove-elements-from-an-array-using-slice-instead-of-splice.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/remove-elements-from-an-array-using-slice-instead-of-splice.md index 082deb8650..9da5369aee 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/remove-elements-from-an-array-using-slice-instead-of-splice.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/remove-elements-from-an-array-using-slice-instead-of-splice.md @@ -1,6 +1,6 @@ --- id: 9d7123c8c441eeafaeb5bdef -title: Remove Elements from an Array Using slice Instead of splice +title: 使用 slice 而不是 splice 从数组中移除元素 challengeType: 1 forumTopicId: 301236 dashedName: remove-elements-from-an-array-using-slice-instead-of-splice @@ -8,37 +8,38 @@ dashedName: remove-elements-from-an-array-using-slice-instead-of-splice # --description-- -A common pattern while working with arrays is when you want to remove items and keep the rest of the array. JavaScript offers the `splice` method for this, which takes arguments for the index of where to start removing items, then the number of items to remove. If the second argument is not provided, the default is to remove items through the end. However, the `splice` method mutates the original array it is called on. Here's an example: +使用数组时经常遇到要删除一些元素并保留数组剩余部分的情况。 为此,JavaScript 提供了 `splice` 方法,它接收两个参数:从哪里开始删除项目的索引,和要删除的项目数。 如果没有提供第二个参数,默认情况下是移除一直到结尾的所有元素。 但 `splice` 方法会改变调用它的原始数组。 举个例子: ```js var cities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"]; -cities.splice(3, 1); // Returns "London" and deletes it from the cities array -// cities is now ["Chicago", "Delhi", "Islamabad", "Berlin"] +cities.splice(3, 1); ``` -As we saw in the last challenge, the `slice` method does not mutate the original array, but returns a new one which can be saved into a variable. Recall that the `slice` method takes two arguments for the indices to begin and end the slice (the end is non-inclusive), and returns those items in a new array. Using the `slice` method instead of `splice` helps to avoid any array-mutating side effects. +在这里 `splice` 返回字符串 `London` 并从城市数组中删除它。 `cities` 将有值 `["Chicago", "Delhi", "Islamabad", "Berlin"]`。 + +正如我们在上一次挑战中看到的那样,`slice` 方法不会改变原始数组,而是返回一个可以保存到变量中的新数组。 回想一下,`slice` 方法接收两个参数,从开始索引开始选取到结束(不包括该元素),并在新数组中返回这些元素。 使用 `slice` 方法替代 `splice` 有助于避免数组变化产生的副作用。 # --instructions-- -Rewrite the function `nonMutatingSplice` by using `slice` instead of `splice`. It should limit the provided `cities` array to a length of 3, and return a new array with only the first three items. +用 `slice` 代替 `splice` 重写 `nonMutatingSplice` 函数。 将 `cities` 数组长度限制为 3,并返回一个仅包含前 3 项的新数组。 -Do not mutate the original array provided to the function. +不要改变提供给函数的原始数组。 # --hints-- -Your code should use the `slice` method. +你的代码中应使用 `slice` 方法。 ```js assert(code.match(/\.slice/g)); ``` -Your code should not use the `splice` method. +不能使用 `splice` 方法。 ```js assert(!code.match(/\.?[\s\S]*?splice/g)); ``` -The `inputCities` array should not change. +不能改变 `inputCities` 数组。 ```js assert( @@ -47,7 +48,7 @@ assert( ); ``` -`nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])` should return `["Chicago", "Delhi", "Islamabad"]`. +`nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])` 应返回 `["Chicago", "Delhi", "Islamabad"]`。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/return-part-of-an-array-using-the-slice-method.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/return-part-of-an-array-using-the-slice-method.md index 75362aa501..bce119c079 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/return-part-of-an-array-using-the-slice-method.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/functional-programming/return-part-of-an-array-using-the-slice-method.md @@ -1,6 +1,6 @@ --- id: 587d7b90367417b2b2512b65 -title: Return Part of an Array Using the slice Method +title: 使用 slice 方法返回数组的一部分 challengeType: 1 forumTopicId: 301239 dashedName: return-part-of-an-array-using-the-slice-method @@ -8,29 +8,30 @@ dashedName: return-part-of-an-array-using-the-slice-method # --description-- -The `slice` method returns a copy of certain elements of an array. It can take two arguments, the first gives the index of where to begin the slice, the second is the index for where to end the slice (and it's non-inclusive). If the arguments are not provided, the default is to start at the beginning of the array through the end, which is an easy way to make a copy of the entire array. The `slice` method does not mutate the original array, but returns a new one. +`slice` 方法可以从已有数组中返回指定元素。 它接受两个参数,第一个规定从何处开始选取,第二个规定从何处结束选取(不包括该元素)。 如果没有传参,则默认为从数组的开头开始到结尾结束,这是复制整个数组的简单方式。 `slice` 返回一个新数组,不会修改原始数组。 -Here's an example: +举个例子: ```js var arr = ["Cat", "Dog", "Tiger", "Zebra"]; var newArray = arr.slice(1, 3); -// Sets newArray to ["Dog", "Tiger"] ``` +`newArray` 值为 `["Dog", "Tiger"]` + # --instructions-- -Use the `slice` method in the `sliceArray` function to return part of the `anim` array given the provided `beginSlice` and `endSlice` indices. The function should return an array. +在 `sliceArray` 函数中使用 `slice` 方法,给出 `beginSlice` 和 `endSlice` 索引,返回 `anim` 数组的一部分。 这个函数应返回一个数组。 # --hints-- -Your code should use the `slice` method. +应该使用 `slice` 方法。 ```js assert(code.match(/\.slice/g)); ``` -The `inputAnim` variable should not change. +不能改变 `inputAnim` 变量。 ```js assert( @@ -39,7 +40,7 @@ assert( ); ``` -`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3)` should return `["Dog", "Tiger"]`. +`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3)` 应返回 `["Dog", "Tiger"]`。 ```js assert( @@ -48,7 +49,7 @@ assert( ); ``` -`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1)` should return `["Cat"]`. +`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1)` 应返回 `["Cat"]`。 ```js assert( @@ -57,7 +58,7 @@ assert( ); ``` -`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4)` should return `["Dog", "Tiger", "Zebra"]`. +`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4)` 应返回 `["Dog", "Tiger", "Zebra"]`。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional.md index c3c51c294d..18d81aa004 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional.md @@ -1,6 +1,6 @@ --- id: a97fd23d9b809dac9921074f -title: Arguments Optional +title: 可选参数 challengeType: 5 forumTopicId: 14271 dashedName: arguments-optional @@ -8,51 +8,51 @@ dashedName: arguments-optional # --description-- -Create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum. +创建一个将两个参数相加的函数。 如果只提供了一个参数,则返回一个需要一个参数并返回总和的函数。 -For example, `addTogether(2, 3)` should return `5`, and `addTogether(2)` should return a function. +比如,`addTogether(2, 3)` 应该返回 `5`。 而 `addTogether(2)` 应该返回一个函数。 -Calling this returned function with a single argument will then return the sum: +调用这个返回的函数,为它传入一个值,会返回两个值的总和: `var sumTwoAnd = addTogether(2);` -`sumTwoAnd(3)` returns `5`. +`sumTwoAnd(3)` 此时应返回 `5`。 -If either argument isn't a valid number, return undefined. +任何时候,只要任一传入的参数不是数字,就应返回 undefined。 # --hints-- -`addTogether(2, 3)` should return 5. +`addTogether(2, 3)` 应返回 5。 ```js assert.deepEqual(addTogether(2, 3), 5); ``` -`addTogether(23, 30)` should return 53. +`addTogether(23, 30)` 应返回 53。 ```js assert.deepEqual(addTogether(23, 30), 53); ``` -`addTogether(5)(7)` should return 12. +`addTogether(5)(7)` 应返回 12。 ```js assert.deepEqual(addTogether(5)(7), 12); ``` -`addTogether("http://bit.ly/IqT6zt")` should return undefined. +`addTogether("http://bit.ly/IqT6zt")` 应返回 `undefined`。 ```js assert.isUndefined(addTogether('http://bit.ly/IqT6zt')); ``` -`addTogether(2, "3")` should return undefined. +`addTogether(2, "3")` 应返回 `undefined`。 ```js assert.isUndefined(addTogether(2, '3')); ``` -`addTogether(2)([3])` should return undefined. +`addTogether(2)([3])` 应返回 `undefined`。 ```js assert.isUndefined(addTogether(2)([3])); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/binary-agents.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/binary-agents.md index 954865c428..5618cdb563 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/binary-agents.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/binary-agents.md @@ -1,6 +1,6 @@ --- id: a8d97bd4c764e91f9d2bda01 -title: Binary Agents +title: 翻译二进制字符串 challengeType: 5 forumTopicId: 14273 dashedName: binary-agents @@ -8,13 +8,13 @@ dashedName: binary-agents # --description-- -Return an English translated sentence of the passed binary string. +请实现一个函数,把传入的二进制字符串转换成英文句子。 -The binary string will be space separated. +二进制字符串会以空格分隔。 # --hints-- -`binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111")` should return "Aren't bonfires fun!?" +`binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111")` 应返回 `Aren't bonfires fun!?`。 ```js assert.deepEqual( @@ -25,7 +25,7 @@ assert.deepEqual( ); ``` -`binaryAgent("01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 01100100 01100101 01000011 01100001 01101101 01110000 00100001")` should return "I love FreeCodeCamp!" +`binaryAgent("01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 01100100 01100101 01000011 01100001 01101101 01110000 00100001")` 应返回 `I love FreeCodeCamp!`。 ```js assert.deepEqual( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/convert-html-entities.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/convert-html-entities.md index 707290ef0c..314b4f31c6 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/convert-html-entities.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/convert-html-entities.md @@ -1,6 +1,6 @@ --- id: a6b0bb188d873cb2c8729495 -title: Convert HTML Entities +title: 转换 HTML 字符实体 challengeType: 5 forumTopicId: 16007 dashedName: convert-html-entities @@ -8,17 +8,17 @@ dashedName: convert-html-entities # --description-- -Convert the characters `&`, `<`, `>`, `"` (double quote), and `'` (apostrophe), in a string to their corresponding HTML entities. +请将字符串中的 `&`、`<`、`>`、`"`(双引号)和 `'`(单引号)转换为相应的 HTML 字符实体。 # --hints-- -`convertHTML("Dolce & Gabbana")` should return `"Dolce & Gabbana"`. +`convertHTML("Dolce & Gabbana")` 应返回 `Dolce & Gabbana`。 ```js assert.match(convertHTML('Dolce & Gabbana'), /Dolce & Gabbana/); ``` -`convertHTML("Hamburgers < Pizza < Tacos")` should return `"Hamburgers < Pizza < Tacos"`. +`convertHTML("Hamburgers < Pizza < Tacos")` 应返回 `Hamburgers < Pizza < Tacos`。 ```js assert.match( @@ -27,13 +27,13 @@ assert.match( ); ``` -`convertHTML("Sixty > twelve")` should return `"Sixty > twelve"`. +`convertHTML("Sixty > twelve")` 应返回 `Sixty > twelve`。 ```js assert.match(convertHTML('Sixty > twelve'), /Sixty > twelve/); ``` -`convertHTML('Stuff in "quotation marks"')` should return `"Stuff in "quotation marks""`. +`convertHTML('Stuff in "quotation marks"')` 应返回 `Stuff in "quotation marks"`。 ```js assert.match( @@ -42,19 +42,19 @@ assert.match( ); ``` -`convertHTML("Schindler's List")` should return `"Schindler's List"`. +`convertHTML("Schindler's List")` 应返回 `Schindler's List`。 ```js assert.match(convertHTML("Schindler's List"), /Schindler's List/); ``` -`convertHTML("<>")` should return `"<>"`. +`convertHTML("<>")` 应返回 `<>`。 ```js assert.match(convertHTML('<>'), /<>/); ``` -`convertHTML("abc")` should return `"abc"`. +`convertHTML("abc")` 应该返回字符串 `abc`。 ```js assert.strictEqual(convertHTML('abc'), 'abc'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/diff-two-arrays.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/diff-two-arrays.md index 228d55cf80..7e437f8c06 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/diff-two-arrays.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/diff-two-arrays.md @@ -1,6 +1,6 @@ --- id: a5de63ebea8dbee56860f4f2 -title: Diff Two Arrays +title: 数组的对称差 challengeType: 5 forumTopicId: 16008 dashedName: diff-two-arrays @@ -8,20 +8,19 @@ dashedName: diff-two-arrays # --description-- -Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays. +比较两个数组并返回一个新数组,包含所有只在其中一个数组中出现的元素,排除两个数组都存在的元素。 换言之,我们需要返回两个数组的对称差。 -**Note** -You can return the array with its elements in any order. +**注意:**返回数组中的元素顺序不会影响挑战的测试结果。 # --hints-- -`diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5])` should return an array. +`diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5])` 应返回一个数组。 ```js assert(typeof diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]) === 'object'); ``` -`["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` should return `["pink wool"]`. +`["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` 应返回 `["pink wool"]`。 ```js assert.sameMembers( @@ -33,7 +32,7 @@ assert.sameMembers( ); ``` -`["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` should return an array with one item. +`["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` 应返回一个长度为 1 的数组。 ```js assert( @@ -44,7 +43,7 @@ assert( ); ``` -`["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` should return `["diorite", "pink wool"]`. +`["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` 应返回 `["diorite", "pink wool"]`。 ```js assert.sameMembers( @@ -56,7 +55,7 @@ assert.sameMembers( ); ``` -`["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` should return an array with two items. +`["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` 应返回一个长度为 2 的数组。 ```js assert( @@ -67,7 +66,7 @@ assert( ); ``` -`["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]` should return `[]`. +`["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]` 应返回 `[]`。 ```js assert.sameMembers( @@ -79,7 +78,7 @@ assert.sameMembers( ); ``` -`["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]` should return an empty array. +`["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]` 应返回一个空数组。 ```js assert( @@ -90,19 +89,19 @@ assert( ); ``` -`[1, 2, 3, 5], [1, 2, 3, 4, 5]` should return `[4]`. +`[1, 2, 3, 5], [1, 2, 3, 4, 5]` 应返回 `[4]`。 ```js assert.sameMembers(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]), [4]); ``` -`[1, 2, 3, 5], [1, 2, 3, 4, 5]` should return an array with one item. +`[1, 2, 3, 5], [1, 2, 3, 4, 5]` 应返回一个长度为 1 的数组。 ```js assert(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]).length === 1); ``` -`[1, "calf", 3, "piglet"], [1, "calf", 3, 4]` should return `["piglet", 4]`. +`[1, "calf", 3, "piglet"], [1, "calf", 3, 4]` 应返回 `["piglet", 4]`。 ```js assert.sameMembers(diffArray([1, 'calf', 3, 'piglet'], [1, 'calf', 3, 4]), [ @@ -111,13 +110,13 @@ assert.sameMembers(diffArray([1, 'calf', 3, 'piglet'], [1, 'calf', 3, 4]), [ ]); ``` -`[1, "calf", 3, "piglet"], [1, "calf", 3, 4]` should return an array with two items. +`[1, "calf", 3, "piglet"], [1, "calf", 3, 4]` 应返回一个长度为 2 的数组。 ```js assert(diffArray([1, 'calf', 3, 'piglet'], [1, 'calf', 3, 4]).length === 2); ``` -`[], ["snuffleupagus", "cookie monster", "elmo"]` should return `["snuffleupagus", "cookie monster", "elmo"]`. +`[], ["snuffleupagus", "cookie monster", "elmo"]` 应返回 `["snuffleupagus", "cookie monster", "elmo"]`。 ```js assert.sameMembers(diffArray([], ['snuffleupagus', 'cookie monster', 'elmo']), [ @@ -127,13 +126,13 @@ assert.sameMembers(diffArray([], ['snuffleupagus', 'cookie monster', 'elmo']), [ ]); ``` -`[], ["snuffleupagus", "cookie monster", "elmo"]` should return an array with three items. +`[], ["snuffleupagus", "cookie monster", "elmo"]` 应返回一个长度为 3 的数组。 ```js assert(diffArray([], ['snuffleupagus', 'cookie monster', 'elmo']).length === 3); ``` -`[1, "calf", 3, "piglet"], [7, "filly"]` should return `[1, "calf", 3, "piglet", 7, "filly"]`. +`[1, "calf", 3, "piglet"], [7, "filly"]` 应返回 `[1, "calf", 3, "piglet", 7, "filly"]`。 ```js assert.sameMembers(diffArray([1, 'calf', 3, 'piglet'], [7, 'filly']), [ @@ -146,7 +145,7 @@ assert.sameMembers(diffArray([1, 'calf', 3, 'piglet'], [7, 'filly']), [ ]); ``` -`[1, "calf", 3, "piglet"], [7, "filly"]` should return an array with six items. +`[1, "calf", 3, "piglet"], [7, "filly"]` 应返回一个长度为 6 的数组。 ```js assert(diffArray([1, 'calf', 3, 'piglet'], [7, 'filly']).length === 6); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/dna-pairing.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/dna-pairing.md index d9f36cd281..6b26aa7ca1 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/dna-pairing.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/dna-pairing.md @@ -1,6 +1,6 @@ --- id: afd15382cdfb22c9efe8b7de -title: DNA Pairing +title: DNA 配对 challengeType: 5 forumTopicId: 16009 dashedName: dna-pairing @@ -8,19 +8,19 @@ dashedName: dna-pairing # --description-- -The DNA strand is missing the pairing element. Take each character, get its pair, and return the results as a 2d array. +给出的 DNA 链上缺少配对元素。 请基于每个字符,获取与其配对的元素,并将结果作为二维数组返回。 -[Base pairs](http://en.wikipedia.org/wiki/Base_pair) are a pair of AT and CG. Match the missing element to the provided character. +DNA 的[碱基对](http://en.wikipedia.org/wiki/Base_pair) 有两种形式:一种是 A 与 T,一种是 C 与 G。 请为参数中给出的每个字符配对相应的碱基。 -Return the provided character as the first element in each array. +注意,参数中给出的字符应作为每个子数组中的第一个元素返回。 -For example, for the input GCG, return \[\["G", "C"], \["C","G"],\["G", "C"]] +例如,传入 `GCG` 时,应返回 `[["G", "C"], ["C","G"], ["G", "C"]]`。 -The character and its pair are paired up in an array, and all the arrays are grouped into one encapsulating array. +字符和它的配对组成一个数组中,所有配对数组放在一个数组里。 # --hints-- -`pairElement("ATCGA")` should return `[["A","T"],["T","A"],["C","G"],["G","C"],["A","T"]]`. +`pairElement("ATCGA")` 应返回 `[["A","T"],["T","A"],["C","G"],["G","C"],["A","T"]]`。 ```js assert.deepEqual(pairElement('ATCGA'), [ @@ -32,7 +32,7 @@ assert.deepEqual(pairElement('ATCGA'), [ ]); ``` -`pairElement("TTGAG")` should return `[["T","A"],["T","A"],["G","C"],["A","T"],["G","C"]]`. +`pairElement("TTGAG")` 应返回 `[["T","A"],["T","A"],["G","C"],["A","T"],["G","C"]]`。 ```js assert.deepEqual(pairElement('TTGAG'), [ @@ -44,7 +44,7 @@ assert.deepEqual(pairElement('TTGAG'), [ ]); ``` -`pairElement("CTCTA")` should return `[["C","G"],["T","A"],["C","G"],["T","A"],["A","T"]]`. +`pairElement("CTCTA")` 应返回 `[["C","G"],["T","A"],["C","G"],["T","A"],["A","T"]]`。 ```js assert.deepEqual(pairElement('CTCTA'), [ diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/drop-it.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/drop-it.md index b2d97fca2f..e2ec44b826 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/drop-it.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/drop-it.md @@ -1,6 +1,6 @@ --- id: a5deed1811a43193f9f1c841 -title: Drop it +title: 根据参数删除数组元素 challengeType: 5 forumTopicId: 16010 dashedName: drop-it @@ -8,13 +8,13 @@ dashedName: drop-it # --description-- -Given the array `arr`, iterate through and remove each element starting from the first element (the 0 index) until the function `func` returns `true` when the iterated element is passed through it. +给定数组 `arr`,从数组的第一个元素开始,用函数 `func` 来检查数组的每个元素是否返回 `true`。 如果返回 false,就把这个元素删除。 持续执行删除操作,直到某个元素传入 func 时返回 true 为止。 -Then return the rest of the array once the condition is satisfied, otherwise, `arr` should be returned as an empty array. +然后在条件满足后返回数组的其余部分,否则, `arr` 应作为空数组返回。 # --hints-- -`dropElements([1, 2, 3, 4], function(n) {return n >= 3;})` should return `[3, 4]`. +`dropElements([1, 2, 3, 4], function(n) {return n >= 3;})` 应返回 `[3, 4]`。 ```js assert.deepEqual( @@ -25,7 +25,7 @@ assert.deepEqual( ); ``` -`dropElements([0, 1, 0, 1], function(n) {return n === 1;})` should return `[1, 0, 1]`. +`dropElements([0, 1, 0, 1], function(n) {return n === 1;})` 应返回 `[1, 0, 1]`。 ```js assert.deepEqual( @@ -36,7 +36,7 @@ assert.deepEqual( ); ``` -`dropElements([1, 2, 3], function(n) {return n > 0;})` should return `[1, 2, 3]`. +`dropElements([1, 2, 3], function(n) {return n > 0;})` 应返回 `[1, 2, 3]`。 ```js assert.deepEqual( @@ -47,7 +47,7 @@ assert.deepEqual( ); ``` -`dropElements([1, 2, 3, 4], function(n) {return n > 5;})` should return `[]`. +`dropElements([1, 2, 3, 4], function(n) {return n > 5;})` 应返回 `[]`。 ```js assert.deepEqual( @@ -58,7 +58,7 @@ assert.deepEqual( ); ``` -`dropElements([1, 2, 3, 7, 4], function(n) {return n > 3;})` should return `[7, 4]`. +`dropElements([1, 2, 3, 7, 4], function(n) {return n > 3;})` 应返回 `[7, 4]`。 ```js assert.deepEqual( @@ -69,7 +69,7 @@ assert.deepEqual( ); ``` -`dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;})` should return `[3, 9, 2]`. +`dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;})` 应返回 `[3, 9, 2]`。 ```js assert.deepEqual( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/everything-be-true.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/everything-be-true.md index 7a93f8ae2a..92df453bd5 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/everything-be-true.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/everything-be-true.md @@ -1,6 +1,6 @@ --- id: a10d2431ad0c6a099a4b8b52 -title: Everything Be True +title: 一切都是True challengeType: 5 forumTopicId: 16011 dashedName: everything-be-true @@ -8,17 +8,17 @@ dashedName: everything-be-true # --description-- -Check if the predicate (second argument) is truthy on all elements of a collection (first argument). +检查谓词(第二个参数)在集合(第一个参数)的所有元素是否为 truthy。 -In other words, you are given an array collection of objects. The predicate `pre` will be an object property and you need to return `true` if its value is `truthy`. Otherwise, return `false`. +换句话说,你将获得一个对象的数组集合。 如果数组中的每个对象里,`pre` 对应属性值均为 `truthy`,则返回 `true`。 否则,返回 `false` 。 -In JavaScript, `truthy` values are values that translate to `true` when evaluated in a Boolean context. +JavaScript 中,如果一个值在 Boolean 的上下文中的执行结果为 `true`,那么我们称这个值是 `truthy` 的。 -Remember, you can access object properties through either dot notation or `[]` notation. +别忘了,你可以使用点号表示法或方括号表示法(`[]`)来访问对象的属性。 # --hints-- -`truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex")` should return true. +`truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex")` 应返回 `true`。 ```js assert.strictEqual( @@ -35,7 +35,7 @@ assert.strictEqual( ); ``` -`truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex")` should return false. +`truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex")` 应返回 `false`。 ```js assert.strictEqual( @@ -52,7 +52,7 @@ assert.strictEqual( ); ``` -`truthCheck([{"user": "Tinky-Winky", "sex": "male", "age": 0}, {"user": "Dipsy", "sex": "male", "age": 3}, {"user": "Laa-Laa", "sex": "female", "age": 5}, {"user": "Po", "sex": "female", "age": 4}], "age")` should return false. +`truthCheck([{"user": "Tinky-Winky", "sex": "male", "age": 0}, {"user": "Dipsy", "sex": "male", "age": 3}, {"user": "Laa-Laa", "sex": "female", "age": 5}, {"user": "Po", "sex": "female", "age": 4}], "age")` 应返回 `false`。 ```js assert.strictEqual( @@ -69,7 +69,7 @@ assert.strictEqual( ); ``` -`truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true}, {"name": "FastForward", "onBoat": null}], "onBoat")` should return false +`truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true}, {"name": "FastForward", "onBoat": null}], "onBoat")` 应返回 `false`。 ```js assert.strictEqual( @@ -85,7 +85,7 @@ assert.strictEqual( ); ``` -`truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true, "alias": "Repete"}, {"name": "FastForward", "onBoat": true}], "onBoat")` should return true +`truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true, "alias": "Repete"}, {"name": "FastForward", "onBoat": true}], "onBoat")` 应返回 `true`。 ```js assert.strictEqual( @@ -101,13 +101,13 @@ assert.strictEqual( ); ``` -`truthCheck([{"single": "yes"}], "single")` should return true +`truthCheck([{"single": "yes"}], "single")` 应返回 `true`。 ```js assert.strictEqual(truthCheck([{ single: 'yes' }], 'single'), true); ``` -`truthCheck([{"single": ""}, {"single": "double"}], "single")` should return false +`truthCheck([{"single": ""}, {"single": "double"}], "single")` 应返回 `false`。 ```js assert.strictEqual( @@ -116,7 +116,7 @@ assert.strictEqual( ); ``` -`truthCheck([{"single": "double"}, {"single": undefined}], "single")` should return false +`truthCheck([{"single": "double"}, {"single": undefined}], "single")` 应返回 `false`。 ```js assert.strictEqual( @@ -125,7 +125,7 @@ assert.strictEqual( ); ``` -`truthCheck([{"single": "double"}, {"single": NaN}], "single")` should return false +`truthCheck([{"single": "double"}, {"single": NaN}], "single")` 应返回 `false`。 ```js assert.strictEqual( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/make-a-person.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/make-a-person.md index b9458749e7..da2d5022c3 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/make-a-person.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/make-a-person.md @@ -1,6 +1,6 @@ --- id: a2f1d72d9b908d0bd72bb9f6 -title: Make a Person +title: 构建 Person 类 challengeType: 5 forumTopicId: 16020 dashedName: make-a-person @@ -8,7 +8,7 @@ dashedName: make-a-person # --description-- -Fill in the object constructor with the following methods below: +用以下方法填充对象构造函数: ```js getFirstName() @@ -19,53 +19,53 @@ setLastName(last) setFullName(firstAndLast) ``` -Run the tests to see the expected output for each method. The methods that take an argument must accept only one argument and it has to be a string. These methods must be the only available means of interacting with the object. +运行测试以查看每个方法的预期输出。 方法接收一个参数,因此必须要有一个参数,并且其类型应该为字符串。 这些方法必须是与对象交互的唯一可用方法。 # --hints-- -`Object.keys(bob).length` should return 6. +`Object.keys(bob).length` 应返回 6。 ```js assert.deepEqual(Object.keys(bob).length, 6); ``` -`bob instanceof Person` should return true. +`bob instanceof Person` 应返回 `true`。 ```js assert.deepEqual(bob instanceof Person, true); ``` -`bob.firstName` should return undefined. +`bob.firstName` 应该返回 `undefined`。 ```js assert.deepEqual(bob.firstName, undefined); ``` -`bob.lastName` should return undefined. +`bob.lastName` 应该返回 `undefined`。 ```js assert.deepEqual(bob.lastName, undefined); ``` -`bob.getFirstName()` should return "Bob". +`bob.getFirstName()` 应该返回字符串 `Bob`. ```js assert.deepEqual(bob.getFirstName(), 'Bob'); ``` -`bob.getLastName()` should return "Ross". +`bob.getLastName()` 应该返回字符串 `Ross`. ```js assert.deepEqual(bob.getLastName(), 'Ross'); ``` -`bob.getFullName()` should return "Bob Ross". +`bob.getFullName()` 应该返回字符串 `Bob Ross`. ```js assert.deepEqual(bob.getFullName(), 'Bob Ross'); ``` -`bob.getFullName()` should return "Haskell Ross" after `bob.setFirstName("Haskell")`. +`bob.getFullName()` 应该在 `bob.setFirstName("Haskell")` 之后返回字符串 `Haskell Ross`。 ```js assert.strictEqual( @@ -77,7 +77,7 @@ assert.strictEqual( ); ``` -`bob.getFullName()` should return "Haskell Curry" after `bob.setLastName("Curry")`. +`bob.getFullName()` 应该在 `bob.setLastName("Curry")` 之后返回字符串 `Haskell Curry`。 ```js assert.strictEqual( @@ -90,7 +90,7 @@ assert.strictEqual( ); ``` -`bob.getFullName()` should return "Haskell Curry" after `bob.setFullName("Haskell Curry")`. +`bob.getFullName()` 应该返回字符串 `Haskell Curry` 之后的 `bob.setFullName("Haskell Curry")`。 ```js assert.strictEqual( @@ -102,7 +102,7 @@ assert.strictEqual( ); ``` -`bob.getFirstName()` should return "Haskell" after `bob.setFullName("Haskell Curry")`. +`bob.getFirstName()` 应该返回字符串 `Haskell` 之后的 `bob.setFullName("Haskell Curry")`。 ```js assert.strictEqual( @@ -114,7 +114,7 @@ assert.strictEqual( ); ``` -`bob.getLastName()` should return "Curry" after `bob.setFullName("Haskell Curry")`. +`bob.getLastName()` 应该返回字符串 `Curry` 之后 `bob.setFullName("Haskell Curry")`。 ```js assert.strictEqual( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/map-the-debris.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/map-the-debris.md index 74118356a4..472c9388ee 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/map-the-debris.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/map-the-debris.md @@ -1,6 +1,6 @@ --- id: af4afb223120f7348cdfc9fd -title: Map the Debris +title: 计算轨道周期 challengeType: 5 forumTopicId: 16021 dashedName: map-the-debris @@ -8,19 +8,19 @@ dashedName: map-the-debris # --description-- -Return a new array that transforms the elements' average altitude into their orbital periods (in seconds). +在这道题目中,我们需要写一个计算天体轨道周期(单位是秒)的函数。 -The array will contain objects in the format `{name: 'name', avgAlt: avgAlt}`. +它接收一个对象数组参数 arr,对象中包含表示天体名称的 name 属性,及表示天体表面平均海拔的 avgAlt 属性。 就像这样:`{name: 'name', avgAlt: avgAlt}`。 -You can read about orbital periods [on Wikipedia](http://en.wikipedia.org/wiki/Orbital_period). +你可以在这条[维基百科](http://en.wikipedia.org/wiki/Orbital_period)的链接中找到轨道周期的计算公式: -The values should be rounded to the nearest whole number. The body being orbited is Earth. +最终的计算结果应取整到最接近的整数。 在这里计算地球的轨道周期。 -The radius of the earth is 6367.4447 kilometers, and the GM value of earth is 398600.4418 km3s-2. +地球半径为 6367.4447 公里,地球的 GM 值为 398600.4418 km 3 s -2 。 # --hints-- -`orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}])` should return `[{name: "sputnik", orbitalPeriod: 86400}]`. +`orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}])` 应返回 `[{name: "sputnik", orbitalPeriod: 86400}]` 。 ```js assert.deepEqual(orbitalPeriod([{ name: 'sputnik', avgAlt: 35873.5553 }]), [ @@ -28,7 +28,7 @@ assert.deepEqual(orbitalPeriod([{ name: 'sputnik', avgAlt: 35873.5553 }]), [ ]); ``` -`orbitalPeriod([{name: "iss", avgAlt: 413.6}, {name: "hubble", avgAlt: 556.7}, {name: "moon", avgAlt: 378632.553}])` should return `[{name : "iss", orbitalPeriod: 5557}, {name: "hubble", orbitalPeriod: 5734}, {name: "moon", orbitalPeriod: 2377399}]`. +`orbitalPeriod([{name: "iss", avgAlt: 413.6}, {name: "hubble", avgAlt: 556.7}, {name: "moon", avgAlt: 378632.553}])` 应返回 `[{name : "iss", orbitalPeriod: 5557}, {name: "hubble", orbitalPeriod: 5734}, {name: "moon", orbitalPeriod: 2377399}]`。 ```js assert.deepEqual( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/missing-letters.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/missing-letters.md index c5e807a7a4..e13495714f 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/missing-letters.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/missing-letters.md @@ -1,6 +1,6 @@ --- id: af7588ade1100bde429baf20 -title: Missing letters +title: 寻找缺失的字母 challengeType: 5 forumTopicId: 16023 dashedName: missing-letters @@ -8,37 +8,37 @@ dashedName: missing-letters # --description-- -Find the missing letter in the passed letter range and return it. +在这道题目中,我们需要写一个函数,找出传入的字符串里缺失的字母并返回它。 -If all letters are present in the range, return undefined. +如果所有字母都在传入的字符串范围内,返回 `undefined`。 # --hints-- -`fearNotLetter("abce")` should return "d". +`fearNotLetter("abce")` 应该返回字符串 `d`。 ```js assert.deepEqual(fearNotLetter('abce'), 'd'); ``` -`fearNotLetter("abcdefghjklmno")` should return "i". +`fearNotLetter("abcdefghjklmno")` 应返回 `i`。 ```js assert.deepEqual(fearNotLetter('abcdefghjklmno'), 'i'); ``` -`fearNotLetter("stvwx")` should return "u". +`fearNotLetter("stvwx")` 应该返回字符串 `u`。 ```js assert.deepEqual(fearNotLetter('stvwx'), 'u'); ``` -`fearNotLetter("bcdf")` should return "e". +`fearNotLetter("bcdf")` 应该返回字符串 `e`。 ```js assert.deepEqual(fearNotLetter('bcdf'), 'e'); ``` -`fearNotLetter("abcdefghijklmnopqrstuvwxyz")` should return undefined. +`fearNotLetter("abcdefghijklmnopqrstuvwxyz")` 应返回 `undefined`。 ```js assert.isUndefined(fearNotLetter('abcdefghijklmnopqrstuvwxyz')); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin.md index af40b695bf..aa29127839 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin.md @@ -1,6 +1,6 @@ --- id: aa7697ea2477d1316795783b -title: Pig Latin +title: 儿童黑话 challengeType: 5 forumTopicId: 16039 dashedName: pig-latin @@ -8,55 +8,55 @@ dashedName: pig-latin # --description-- -Pig Latin is a way of altering English Words. The rules are as follows: +儿童黑话也叫 Pig Latin,是一种英语语言游戏。 规则如下: -\- If a word begins with a consonant, take the first consonant or consonant cluster, move it to the end of the word, and add "ay" to it. +\- 如果单词以辅音开头,就把第一个辅音字母或第一组辅音簇移到单词的结尾,并在后面加上 `ay`。 -\- If a word begins with a vowel, just add "way" at the end. +\- 如果单词以元音开头,只需要在结尾加上 `way`。 # --instructions-- -Translate the provided string to Pig Latin. Input strings are guaranteed to be English words in all lowercase. +请把传入的字符串根据上述规则翻译成儿童黑话并返回结果。 输入的字符串一定是一个小写的英文单词。 # --hints-- -`translatePigLatin("california")` should return "aliforniacay". +`translatePigLatin("california")` 应该返回字符串 `aliforniacay`。 ```js assert.deepEqual(translatePigLatin('california'), 'aliforniacay'); ``` -`translatePigLatin("paragraphs")` should return "aragraphspay". +`translatePigLatin("paragraphs")` 应该返回字符串 `aragraphspay`。 ```js assert.deepEqual(translatePigLatin('paragraphs'), 'aragraphspay'); ``` -`translatePigLatin("glove")` should return "oveglay". +`translatePigLatin("glove")` 应该返回字符串 `oveglay`。 ```js assert.deepEqual(translatePigLatin('glove'), 'oveglay'); ``` -`translatePigLatin("algorithm")` should return "algorithmway". +`translatePigLatin("algorithm")` 应该返回字符串 `algorithmway`。 ```js assert.deepEqual(translatePigLatin('algorithm'), 'algorithmway'); ``` -`translatePigLatin("eight")` should return "eightway". +`translatePigLatin("eight")` 应该返回字符串 `eightway`。 ```js assert.deepEqual(translatePigLatin('eight'), 'eightway'); ``` -Should handle words where the first vowel comes in the middle of the word. `translatePigLatin("schwartz")` should return "artzschway". +应该处理单词的第一个元音在单词中间的位置的情况。 `translatePigLatin("schwartz")` 应该返回字符串 `artzschway`。 ```js assert.deepEqual(translatePigLatin('schwartz'), 'artzschway'); ``` -Should handle words without vowels. `translatePigLatin("rhythm")` should return "rhythmay". +应该处理不带元音的单词。 `translatePigLatin("rhythm")` 应该返回字符串 `rhythmay`。 ```js assert.deepEqual(translatePigLatin('rhythm'), 'rhythmay'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace.md index f4ca7362bd..0a9868bf4a 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace.md @@ -1,6 +1,6 @@ --- id: a0b5010f579e69b815e7c5d6 -title: Search and Replace +title: 搜索与替换 challengeType: 5 forumTopicId: 16045 dashedName: search-and-replace @@ -8,20 +8,19 @@ dashedName: search-and-replace # --description-- -Perform a search and replace on the sentence using the arguments provided and return the new sentence. +在这道题目中,我们需要写一个字符串的搜索与替换函数,它的返回值为完成替换后的新字符串。 -First argument is the sentence to perform the search and replace on. +这个函数接收的第一个参数为待替换的句子。 -Second argument is the word that you will be replacing (before). +第二个参数为句中需要被替换的单词。 -Third argument is what you will be replacing the second argument with (after). +第三个参数为替换后的单词。 -**Note** -Preserve the case of the first character in the original word when you are replacing it. For example if you mean to replace the word "Book" with the word "dog", it should be replaced as "Dog" +**注意:** 在更换原始单词时保留原始单词中第一个字符的大小写。 即如果传入的第二个参数为 `Book`,第三个参数为 `dog`,那么替换后的结果应为 `Dog` # --hints-- -`myReplace("Let us go to the store", "store", "mall")` should return "Let us go to the mall". +`myReplace("Let us go to the store", "store", "mall")` 应返回 `Let us go to the mall`。 ```js assert.deepEqual( @@ -30,7 +29,7 @@ assert.deepEqual( ); ``` -`myReplace("He is Sleeping on the couch", "Sleeping", "sitting")` should return "He is Sitting on the couch". +`myReplace("He is Sleeping on the couch", "Sleeping", "sitting")` 应返回 `He is Sitting on the couch`。 ```js assert.deepEqual( @@ -39,7 +38,7 @@ assert.deepEqual( ); ``` -`myReplace("I think we should look up there", "up", "Down")` should return "I think we should look down there". +`myReplace("I think we should look up there", "up", "Down")` 应返回 `I think we should look down there`。 ```js assert.deepEqual( @@ -48,7 +47,7 @@ assert.deepEqual( ); ``` -`myReplace("This has a spellngi error", "spellngi", "spelling")` should return "This has a spelling error". +`myReplace("This has a spellngi error", "spellngi", "spelling")` 应返回 `This has a spelling error`。 ```js assert.deepEqual( @@ -57,7 +56,7 @@ assert.deepEqual( ); ``` -`myReplace("His name is Tom", "Tom", "john")` should return "His name is John". +`myReplace("His name is Tom", "Tom", "john")` 应返回 `His name is John`。 ```js assert.deepEqual( @@ -66,7 +65,7 @@ assert.deepEqual( ); ``` -`myReplace("Let us get back to more Coding", "Coding", "algorithms")` should return "Let us get back to more Algorithms". +`myReplace("Let us get back to more Coding", "Coding", "algorithms")` 应返回 `Let us get back to more Algorithms`。 ```js assert.deepEqual( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy.md index 5fbf7d5aa8..2d61e2d41f 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy.md @@ -1,6 +1,6 @@ --- id: a39963a4c10bc8b4d4f06d7e -title: Seek and Destroy +title: 过滤数组元素 challengeType: 5 forumTopicId: 16046 dashedName: seek-and-destroy @@ -8,38 +8,37 @@ dashedName: seek-and-destroy # --description-- -You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments. +你将获得一个初始数组(`destroyer` 函数中的第一个参数),后跟一个或多个参数。 从初始数组中移除所有与后续参数相等的元素。 -**Note** -You have to use the `arguments` object. +**注意:** 你可以使用 `arguments` 对象。 # --hints-- -`destroyer([1, 2, 3, 1, 2, 3], 2, 3)` should return `[1, 1]`. +`destroyer([1, 2, 3, 1, 2, 3], 2, 3)` 应返回 `[1, 1]`。 ```js assert.deepEqual(destroyer([1, 2, 3, 1, 2, 3], 2, 3), [1, 1]); ``` -`destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3)` should return `[1, 5, 1]`. +`destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3)` 应返回 `[1, 5, 1]`。 ```js assert.deepEqual(destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3), [1, 5, 1]); ``` -`destroyer([3, 5, 1, 2, 2], 2, 3, 5)` should return `[1]`. +`destroyer([3, 5, 1, 2, 2], 2, 3, 5)` 应返回 `[1]`。 ```js assert.deepEqual(destroyer([3, 5, 1, 2, 2], 2, 3, 5), [1]); ``` -`destroyer([2, 3, 2, 3], 2, 3)` should return `[]`. +`destroyer([2, 3, 2, 3], 2, 3)` 应返回 `[]`。 ```js assert.deepEqual(destroyer([2, 3, 2, 3], 2, 3), []); ``` -`destroyer(["tree", "hamburger", 53], "tree", 53)` should return `["hamburger"]`. +`destroyer(["tree", "hamburger", 53], "tree", 53)` 应返回 `["hamburger"]`。 ```js assert.deepEqual(destroyer(['tree', 'hamburger', 53], 'tree', 53), [ @@ -47,7 +46,7 @@ assert.deepEqual(destroyer(['tree', 'hamburger', 53], 'tree', 53), [ ]); ``` -`destroyer(["possum", "trollo", 12, "safari", "hotdog", 92, 65, "grandma", "bugati", "trojan", "yacht"], "yacht", "possum", "trollo", "safari", "hotdog", "grandma", "bugati", "trojan")` should return `[12,92,65]`. +`destroyer(["possum", "trollo", 12, "safari", "hotdog", 92, 65, "grandma", "bugati", "trojan", "yacht"], "yacht", "possum", "trollo", "safari", "hotdog", "grandma", "bugati", "trojan")` 应返回 `[12,92,65]`。 ```js assert.deepEqual( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple.md index e6c39f5ee6..2c8092ea41 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple.md @@ -1,6 +1,6 @@ --- id: ae9defd7acaf69703ab432ea -title: Smallest Common Multiple +title: 找出数字范围内的最小公倍数 challengeType: 5 forumTopicId: 16075 dashedName: smallest-common-multiple @@ -8,45 +8,45 @@ dashedName: smallest-common-multiple # --description-- -Find the smallest common multiple of the provided parameters that can be evenly divided by both, as well as by all sequential numbers in the range between these parameters. +找到给定参数的最小公倍数,可以被这两个参数整除,也可以被指定范围内的所以整数整除。 -The range will be an array of two numbers that will not necessarily be in numerical order. +注意,较小数不一定总是出现在数组的第一个元素。 -For example, if given 1 and 3, find the smallest common multiple of both 1 and 3 that is also evenly divisible by all numbers *between* 1 and 3. The answer here would be 6. +例如,如果给定 1 和 3,找到 1 和 3 的最小公倍数,也可以被 1 到 3 *之间*的所有数字整除。 这里的答案将是 6。 # --hints-- -`smallestCommons([1, 5])` should return a number. +`smallestCommons([1, 5])` 应返回 a number。 ```js assert.deepEqual(typeof smallestCommons([1, 5]), 'number'); ``` -`smallestCommons([1, 5])` should return 60. +`smallestCommons([1, 5])` 应返回 60。 ```js assert.deepEqual(smallestCommons([1, 5]), 60); ``` -`smallestCommons([5, 1])` should return 60. +`smallestCommons([5, 1])` 应返回 60。 ```js assert.deepEqual(smallestCommons([5, 1]), 60); ``` -`smallestCommons([2, 10])` should return 2520. +`smallestCommons([2, 10])` 应返回 2520。 ```js assert.deepEqual(smallestCommons([2, 10]), 2520); ``` -`smallestCommons([1, 13])` should return 360360. +`smallestCommons([1, 13])` 应返回 360360。 ```js assert.deepEqual(smallestCommons([1, 13]), 360360); ``` -`smallestCommons([23, 18])` should return 6056820. +`smallestCommons([23, 18])` 应返回 6056820。 ```js assert.deepEqual(smallestCommons([23, 18]), 6056820); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union.md index cbc9cd794a..d625992eea 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union.md @@ -1,6 +1,6 @@ --- id: a105e963526e7de52b219be9 -title: Sorted Union +title: 集合排序 challengeType: 5 forumTopicId: 16077 dashedName: sorted-union @@ -8,29 +8,29 @@ dashedName: sorted-union # --description-- -Write a function that takes two or more arrays and returns a new array of unique values in the order of the original provided arrays. +编写一个带有两个或更多数组的函数,并按原始提供的数组的顺序返回一个新的唯一值数组。 -In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array. +换句话说,所有数组中出现的所有值都应按其原始顺序包括在内,但最终数组中不得重复。 -The unique numbers should be sorted by their original order, but the final array should not be sorted in numerical order. +去重后的数字应按其出现在参数中的原始顺序排序,最终数组不应按数字大小进行排序。 -Check the assertion tests for examples. +如有疑问,请先浏览下方的测试用例。 # --hints-- -`uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1])` should return `[1, 3, 2, 5, 4]`. +`uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1])` 应返回 `[1, 3, 2, 5, 4]`。 ```js assert.deepEqual(uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]), [1, 3, 2, 5, 4]); ``` -`uniteUnique([1, 2, 3], [5, 2, 1])` should return `[1, 2, 3, 5]`. +`uniteUnique([1, 2, 3], [5, 2, 1])` 应返回 `[1, 2, 3, 5]`。 ```js assert.deepEqual(uniteUnique([1, 2, 3], [5, 2, 1]), [1, 2, 3, 5]); ``` -`uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8])` should return `[1, 2, 3, 5, 4, 6, 7, 8]`. +`uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8])` 应返回 `[1, 2, 3, 5, 4, 6, 7, 8]`。 ```js assert.deepEqual(uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8]), [ diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/spinal-tap-case.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/spinal-tap-case.md index c68938ce89..993154a39c 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/spinal-tap-case.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/spinal-tap-case.md @@ -1,6 +1,6 @@ --- id: a103376db3ba46b2d50db289 -title: Spinal Tap Case +title: 短线连接格式 challengeType: 5 forumTopicId: 16078 dashedName: spinal-tap-case @@ -8,23 +8,23 @@ dashedName: spinal-tap-case # --description-- -Convert a string to spinal case. Spinal case is all-lowercase-words-joined-by-dashes. +将字符串转换为短线连接格式。 短线连接格式是小写单词全部小写并以破折号分隔。 # --hints-- -`spinalCase("This Is Spinal Tap")` should return `"this-is-spinal-tap"`. +`spinalCase("This Is Spinal Tap")` 应返回 `this-is-spinal-tap`。 ```js assert.deepEqual(spinalCase('This Is Spinal Tap'), 'this-is-spinal-tap'); ``` -`spinalCase("thisIsSpinalTap")` should return `"this-is-spinal-tap"`. +`spinalCase("thisIsSpinalTap")` 应返回 `this-is-spinal-tap`。 ```js assert.strictEqual(spinalCase('thisIsSpinalTap'), 'this-is-spinal-tap'); ``` -`spinalCase("The_Andy_Griffith_Show")` should return `"the-andy-griffith-show"`. +`spinalCase("The_Andy_Griffith_Show")` 应返回 `the-andy-griffith-show`。 ```js assert.strictEqual( @@ -33,7 +33,7 @@ assert.strictEqual( ); ``` -`spinalCase("Teletubbies say Eh-oh")` should return `"teletubbies-say-eh-oh"`. +`spinalCase("Teletubbies say Eh-oh")` 应返回 `teletubbies-say-eh-oh`。 ```js assert.strictEqual( @@ -42,7 +42,7 @@ assert.strictEqual( ); ``` -`spinalCase("AllThe-small Things")` should return `"all-the-small-things"`. +`spinalCase("AllThe-small Things")` 应返回 `all-the-small-things`。 ```js assert.strictEqual(spinalCase('AllThe-small Things'), 'all-the-small-things'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller.md index 5744ab7e20..434e0d47af 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller.md @@ -1,6 +1,6 @@ --- id: ab306dbdcc907c7ddfc30830 -title: Steamroller +title: 数组扁平化 challengeType: 5 forumTopicId: 16079 dashedName: steamroller @@ -8,35 +8,35 @@ dashedName: steamroller # --description-- -Flatten a nested array. You must account for varying levels of nesting. +嵌套数组扁平化成一维数组。 必须考虑到各种深度的嵌套层级。 # --hints-- -`steamrollArray([[["a"]], [["b"]]])` should return `["a", "b"]`. +`steamrollArray([[["a"]], [["b"]]])` 应返回 `["a", "b"]`。 ```js assert.deepEqual(steamrollArray([[['a']], [['b']]]), ['a', 'b']); ``` -`steamrollArray([1, [2], [3, [[4]]]])` should return `[1, 2, 3, 4]`. +`steamrollArray([1, [2], [3, [[4]]]])` 应返回 `[1, 2, 3, 4]`。 ```js assert.deepEqual(steamrollArray([1, [2], [3, [[4]]]]), [1, 2, 3, 4]); ``` -`steamrollArray([1, [], [3, [[4]]]])` should return `[1, 3, 4]`. +`steamrollArray([1, [], [3, [[4]]]])` 应返回 `[1, 3, 4]`。 ```js assert.deepEqual(steamrollArray([1, [], [3, [[4]]]]), [1, 3, 4]); ``` -`steamrollArray([1, {}, [3, [[4]]]])` should return `[1, {}, 3, 4]`. +`steamrollArray([1, {}, [3, [[4]]]])` 应返回 `[1, {}, 3, 4]`。 ```js assert.deepEqual(steamrollArray([1, {}, [3, [[4]]]]), [1, {}, 3, 4]); ``` -Your solution should not use the `Array.prototype.flat()` or `Array.prototype.flatMap()` methods. +代码中不应使用 `Array.prototype.flat()` 或 `Array.prototype.flatMap()` 方法。 ```js assert(!code.match(/\.\s*flat\s*\(/) && !code.match(/\.\s*flatMap\s*\(/)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-numbers-in-a-range.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-numbers-in-a-range.md index a7dbdaeecc..28df6db9c7 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-numbers-in-a-range.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-numbers-in-a-range.md @@ -1,6 +1,6 @@ --- id: a3566b1109230028080c9345 -title: Sum All Numbers in a Range +title: 范围内的数字求和 challengeType: 5 forumTopicId: 16083 dashedName: sum-all-numbers-in-a-range @@ -8,37 +8,37 @@ dashedName: sum-all-numbers-in-a-range # --description-- -We'll pass you an array of two numbers. Return the sum of those two numbers plus the sum of all the numbers between them. The lowest number will not always come first. +我们会传入一个由两个数字组成的数组。 给出一个含有两个数字的数组,我们需要写一个函数,让它返回这两个数字间所有数字(包含这两个数字)的总和。 最低的数字并不总是第一位。 -For example, `sumAll([4,1])` should return `10` because sum of all the numbers between 1 and 4 (both inclusive) is `10`. +例如,`sumAll([4,1])` 应返回 `10`,因为从 1 到 4(包含 1、4)的所有数字的和是 `10`。 # --hints-- -`sumAll([1, 4])` should return a number. +`sumAll([1, 4])` 应返回一个数字。 ```js assert(typeof sumAll([1, 4]) === 'number'); ``` -`sumAll([1, 4])` should return 10. +`sumAll([1, 4])` 应返回 10。 ```js assert.deepEqual(sumAll([1, 4]), 10); ``` -`sumAll([4, 1])` should return 10. +`sumAll([4, 1])` 应返回 10。 ```js assert.deepEqual(sumAll([4, 1]), 10); ``` -`sumAll([5, 10])` should return 45. +`sumAll([5, 10])` 应返回 45。 ```js assert.deepEqual(sumAll([5, 10]), 45); ``` -`sumAll([10, 5])` should return 45. +`sumAll([10, 5])` 应返回 45。 ```js assert.deepEqual(sumAll([10, 5]), 45); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers.md index 0c5b625e71..8d4de6a544 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers.md @@ -1,6 +1,6 @@ --- id: a5229172f011153519423690 -title: Sum All Odd Fibonacci Numbers +title: 求斐波那契数列中的奇数之和 challengeType: 5 forumTopicId: 16084 dashedName: sum-all-odd-fibonacci-numbers @@ -8,45 +8,45 @@ dashedName: sum-all-odd-fibonacci-numbers # --description-- -Given a positive integer `num`, return the sum of all odd Fibonacci numbers that are less than or equal to `num`. +在这道题目中,我们需要写一个函数,参数为一个正整数 `num`,返回值为斐波那契数列中,小于或等于 `num` 的奇数之和。 -The first two numbers in the Fibonacci sequence are 1 and 1. Every additional number in the sequence is the sum of the two previous numbers. The first six numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8. +斐波那契数列中,第一和第二个数字都是 1。 后面的每个数字由之前两数相加得出。 斐波那契数列的前六个数字分别为:1、1、2、3、5、8。 -For example, `sumFibs(10)` should return `10` because all odd Fibonacci numbers less than or equal to `10` are 1, 1, 3, and 5. +比如,`sumFibs(10)` 应该返回 `10`。 因为斐波那契数列中,比 `10` 小的数字只有 1、1、3、5。 # --hints-- -`sumFibs(1)` should return a number. +`sumFibs(1)` 应返回一个数字。 ```js assert(typeof sumFibs(1) === 'number'); ``` -`sumFibs(1000)` should return 1785. +`sumFibs(1000)` 应返回 1785。 ```js assert(sumFibs(1000) === 1785); ``` -`sumFibs(4000000)` should return 4613732. +`sumFibs(4000000)` 应返回 4613732。 ```js assert(sumFibs(4000000) === 4613732); ``` -`sumFibs(4)` should return 5. +`sumFibs(4)` 应返回 5。 ```js assert(sumFibs(4) === 5); ``` -`sumFibs(75024)` should return 60696. +`sumFibs(75024)` 应返回 60696。 ```js assert(sumFibs(75024) === 60696); ``` -`sumFibs(75025)` should return 135721. +`sumFibs(75025)` 应返回 135721。 ```js assert(sumFibs(75025) === 135721); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes.md index 57295dd11e..c0c21e9d65 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes.md @@ -1,6 +1,6 @@ --- id: a3bfc1673c0526e06d3ac698 -title: Sum All Primes +title: 质数求和 challengeType: 5 forumTopicId: 16085 dashedName: sum-all-primes @@ -8,25 +8,25 @@ dashedName: sum-all-primes # --description-- -A prime number is a whole number greater than 1 with exactly two divisors: 1 and itself. For example, 2 is a prime number because it is only divisible by 1 and 2. In contrast, 4 is not prime since it is divisible by 1, 2 and 4. +质数(prime number)是大于 1 且仅可以被 1 和自己整除的数。 比如,2 就是一个质数,因为它只可以被 1 和 2(它本身)整除。 相反,4 不是质数,因为它可以被 1, 2 和 4 整除。 -Rewrite `sumPrimes` so it returns the sum of all prime numbers that are less than or equal to num. +请完成 `sumPrimes` 方法,使其返回小于等于传入参数数字的所有质数之和。 # --hints-- -`sumPrimes(10)` should return a number. +`sumPrimes(10)` 应返回一个数字。 ```js assert.deepEqual(typeof sumPrimes(10), 'number'); ``` -`sumPrimes(10)` should return 17. +`sumPrimes(10)` 应返回 17。 ```js assert.deepEqual(sumPrimes(10), 17); ``` -`sumPrimes(977)` should return 73156. +`sumPrimes(977)` 应返回 73156。 ```js assert.deepEqual(sumPrimes(977), 73156); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou.md index b0a565be94..f972afdc1e 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou.md @@ -1,6 +1,6 @@ --- id: a8e512fbe388ac2f9198f0fa -title: Wherefore art thou +title: 找出包含特定键值对的对象 challengeType: 5 forumTopicId: 16092 dashedName: wherefore-art-thou @@ -8,13 +8,13 @@ dashedName: wherefore-art-thou # --description-- -Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching name and value pairs (second argument). Each name and value pair of the source object has to be present in the object from the collection if it is to be included in the returned array. +创建一个查看对象数组(第一个参数)的函数,并返回具有匹配的名称和值对的所有对象的数组(第二个参数)。 如果要包含在返回的数组中,则源对象的每个名称和值对都必须存在于集合中的对象中。 -For example, if the first argument is `[{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }]`, and the second argument is `{ last: "Capulet" }`, then you must return the third object from the array (the first argument), because it contains the name and its value, that was passed on as the second argument. +比如,如果第一个参数是 `[{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }]`,第二个参数是 `{ last: "Capulet" }`。 # --hints-- -`whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" })` should return `[{ first: "Tybalt", last: "Capulet" }]`. +`whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" })` 应返回 `[{ first: "Tybalt", last: "Capulet" }]`。 ```js assert.deepEqual( @@ -30,7 +30,7 @@ assert.deepEqual( ); ``` -`whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 })` should return `[{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }]`. +`whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 })` 应返回 `[{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }]`。 ```js assert.deepEqual( @@ -41,7 +41,7 @@ assert.deepEqual( ); ``` -`whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 })` should return `[{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }]`. +`whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 })` 应返回 `[{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }]`。 ```js assert.deepEqual( @@ -56,7 +56,7 @@ assert.deepEqual( ); ``` -`whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 })` should return `[{ "apple": 1, "bat": 2, "cookie": 2 }]`. +`whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 })` 应返回 `[{ "apple": 1, "bat": 2, "cookie": 2 }]`。 ```js assert.deepEqual( @@ -68,7 +68,7 @@ assert.deepEqual( ); ``` -`whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 })` should return `[{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }]`. +`whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 })` 应返回 `[{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }]`。 ```js assert.deepEqual( @@ -88,7 +88,7 @@ assert.deepEqual( ); ``` -`whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3})` should return `[]` +`whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3})` 应返回 `[]`。 ```js assert.deepEqual( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher.md index 7e0a8c9f36..2b7edcaa94 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher.md @@ -1,6 +1,6 @@ --- id: 56533eb9ac21ba0edf2244e2 -title: Caesars Cipher +title: 凯撒密码 challengeType: 5 forumTopicId: 16003 dashedName: caesars-cipher @@ -8,35 +8,35 @@ dashedName: caesars-cipher # --description-- -One of the simplest and most widely known ciphers is a Caesar cipher, also known as a shift cipher. In a shift cipher the meanings of the letters are shifted by some set amount. +凯撒密码( Caesar cipher)是最简单且最广为人知的密码(ciphers),也被称为移位密码(shift cipher)。 在移位密码中,明文中的字母通过按照一个固定数目进行偏移后被替换成新的字母。 -A common modern use is the [ROT13](https://en.wikipedia.org/wiki/ROT13) cipher, where the values of the letters are shifted by 13 places. Thus 'A' ↔ 'N', 'B' ↔ 'O' and so on. +[ROT13](https://en.wikipedia.org/wiki/ROT13) 是一个被广泛使用的加密技术,明文中的所有字母都被移动 13 位。 也就是, `A ↔ N`,`B ↔ O` 等等。 -Write a function which takes a [ROT13](https://en.wikipedia.org/wiki/ROT13) encoded string as input and returns a decoded string. +编写一个函数,它将 [ROT13](https://en.wikipedia.org/wiki/ROT13) 编码的字符串作为输入并返回解码字符串。 -All letters will be uppercase. Do not transform any non-alphabetic character (i.e. spaces, punctuation), but do pass them on. +所有解码后的字母都必须为字母大写。 请不要解码非字母的字符(例如,空格、标点符号),但你需要在结果中保留它们。 # --hints-- -`rot13("SERR PBQR PNZC")` should decode to `FREE CODE CAMP` +`rot13("SERR PBQR PNZC")` 应解码为 `FREE CODE CAMP` ```js assert(rot13('SERR PBQR PNZC') === 'FREE CODE CAMP'); ``` -`rot13("SERR CVMMN!")` should decode to `FREE PIZZA!` +`rot13("SERR CVMMN!")` 应解码为 `FREE PIZZA!` ```js assert(rot13('SERR CVMMN!') === 'FREE PIZZA!'); ``` -`rot13("SERR YBIR?")` should decode to `FREE LOVE?` +`rot13("SERR YBIR?")` 应解码为 `FREE LOVE?` ```js assert(rot13('SERR YBIR?') === 'FREE LOVE?'); ``` -`rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.")` should decode to `THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.` +`rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.")` 应解码为 `THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.` ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register.md index 49336bf373..f89918bebd 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register.md @@ -1,6 +1,6 @@ --- id: aa2e6f85cab2ab736c9a9b24 -title: Cash Register +title: 计算找零 challengeType: 5 forumTopicId: 16012 dashedName: cash-register @@ -8,21 +8,21 @@ dashedName: cash-register # --description-- -Design a cash register drawer function `checkCashRegister()` that accepts purchase price as the first argument (`price`), payment as the second argument (`cash`), and cash-in-drawer (`cid`) as the third argument. +请编写一个用于收银机的函数 `checkCashRegister()`:它的第一个参数为售价 `price`、第二个参数为支付金额 `cash`、第三个参数为收银机內的金额 `cid`。 -`cid` is a 2D array listing available currency. +`cid` 是包含货币面值的二维数组。 -The `checkCashRegister()` function should always return an object with a `status` key and a `change` key. +函数 `checkCashRegister()` 应返回含有 `status` 属性和 `change` 属性的对象。 -Return `{status: "INSUFFICIENT_FUNDS", change: []}` if cash-in-drawer is less than the change due, or if you cannot return the exact change. +如果收银机內的金额少于应找回的零钱数,或者你无法返回确切的数目时,返回 `{status: "INSUFFICIENT_FUNDS", change: []}`。 -Return `{status: "CLOSED", change: [...]}` with cash-in-drawer as the value for the key `change` if it is equal to the change due. +如果收银机內的金额恰好等于应找回的零钱数,返回 `{status: "CLOSED", change: [...]}`,其中 `change` 的属性值就是收银机內的金额。 -Otherwise, return `{status: "OPEN", change: [...]}`, with the change due in coins and bills, sorted in highest to lowest order, as the value of the `change` key. +否则,返回 `{status: "OPEN", change: [...]}`,其中 `change` 键值是应找回的零钱数,并将找零的面值由高到低排序。 -
Currency UnitAmount
Penny$0.01 (PENNY)
Nickel$0.05 (NICKEL)
Dime$0.1 (DIME)
Quarter$0.25 (QUARTER)
Dollar$1 (ONE)
Five Dollars$5 (FIVE)
Ten Dollars$10 (TEN)
Twenty Dollars$20 (TWENTY)
One-hundred Dollars$100 (ONE HUNDRED)
+
货币单位 Unit面值
Penny0.01 美元(PENNY)
Nickel0.05 美元(NICKEL)
Dime0.1 美元(DIME)
Quarter0.25 美元(QUARTER)
Dollar1 美元(ONE)
Five Dollars5 美元(五)
Ten Dollars10 美元(TEN)
Twenty Dollars20 美元(TWENTY)
One-hundred Dollars100美元(ONE HUNDRED)
-See below for an example of a cash-in-drawer array: +下面的抽屉里现金数组示例: ```js [ @@ -40,7 +40,7 @@ See below for an example of a cash-in-drawer array: # --hints-- -`checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])` should return an object. +`checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])` 应返回一个对象。 ```js assert.deepEqual( @@ -61,7 +61,7 @@ assert.deepEqual( ); ``` -`checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])` should return `{status: "OPEN", change: [["QUARTER", 0.5]]}`. +`checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])` 应返回 `{status: "OPEN", change: [["QUARTER", 0.5]]}`。 ```js assert.deepEqual( @@ -80,7 +80,7 @@ assert.deepEqual( ); ``` -`checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])` should return `{status: "OPEN", change: [["TWENTY", 60], ["TEN", 20], ["FIVE", 15], ["ONE", 1], ["QUARTER", 0.5], ["DIME", 0.2], ["PENNY", 0.04]]}`. +`checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])` 应返回 `{status: "OPEN", change: [["TWENTY", 60], ["TEN", 20], ["FIVE", 15], ["ONE", 1], ["QUARTER", 0.5], ["DIME", 0.2], ["PENNY", 0.04]]}`。 ```js assert.deepEqual( @@ -110,7 +110,7 @@ assert.deepEqual( ); ``` -`checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])` should return `{status: "INSUFFICIENT_FUNDS", change: []}`. +`checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])` 应返回 `{status: "INSUFFICIENT_FUNDS", change: []}`。 ```js assert.deepEqual( @@ -129,7 +129,7 @@ assert.deepEqual( ); ``` -`checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])` should return `{status: "INSUFFICIENT_FUNDS", change: []}`. +`checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])` 应返回 `{status: "INSUFFICIENT_FUNDS", change: []}`。 ```js assert.deepEqual( @@ -148,7 +148,7 @@ assert.deepEqual( ); ``` -`checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])` should return `{status: "CLOSED", change: [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]}`. +`checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])` 应返回 `{status: "CLOSED", change: [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]}`。 ```js assert.deepEqual( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/palindrome-checker.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/palindrome-checker.md index 49ec05e0e8..bac2fbf13c 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/palindrome-checker.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/palindrome-checker.md @@ -1,6 +1,6 @@ --- id: aaa48de84e1ecc7c742e1124 -title: Palindrome Checker +title: 回文检查器 challengeType: 5 forumTopicId: 16004 dashedName: palindrome-checker @@ -8,91 +8,91 @@ dashedName: palindrome-checker # --description-- -Return `true` if the given string is a palindrome. Otherwise, return `false`. +如果传入的字符串是回文字符串,则返回 `true`。 否则返回 `false` -A palindrome is a word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing. +回文 palindrome,指在忽略标点符号、大小写和空格的前提下,正着读和反着读一模一样。 -**Note:** You'll need to remove **all non-alphanumeric characters** (punctuation, spaces and symbols) and turn everything into the same case (lower or upper case) in order to check for palindromes. +**注意:**检查回文时,你需要先去除**所有非字母数字的字符**(标点、空格和符号),并将所有字母都转换成大写或都转换成小写。 -We'll pass strings with varying formats, such as `"racecar"`, `"RaceCar"`, and `"race CAR"` among others. +我们会传入具有不同格式的字符串,如 `racecar`、`RaceCar` 和 `race CAR` 等等。 -We'll also pass strings with special symbols, such as `"2A3*3a2"`, `"2A3 3a2"`, and `"2_A3*3#A2"`. +我们也会传入一些包含特殊符号的字符串,例如 `2A3*3a2`、`2A3 3a2`、`2_A3*3#A2`。 # --hints-- -`palindrome("eye")` should return a boolean. +`palindrome("eye")` 应返回一个布尔值。 ```js assert(typeof palindrome('eye') === 'boolean'); ``` -`palindrome("eye")` should return true. +`palindrome("eye")` 应返回 `true`。 ```js assert(palindrome('eye') === true); ``` -`palindrome("_eye")` should return true. +`palindrome("_eye")` 应返回 `true`。 ```js assert(palindrome('_eye') === true); ``` -`palindrome("race car")` should return true. +`palindrome("race car")` 应返回 `true`。 ```js assert(palindrome('race car') === true); ``` -`palindrome("not a palindrome")` should return false. +`palindrome("not a palindrome")` 应返回 `false`。 ```js assert(palindrome('not a palindrome') === false); ``` -`palindrome("A man, a plan, a canal. Panama")` should return true. +`palindrome("A man, a plan, a canal. Panama")` 应返回 `true`。 ```js assert(palindrome('A man, a plan, a canal. Panama') === true); ``` -`palindrome("never odd or even")` should return true. +`palindrome("never odd or even")` 应返回 `true`。 ```js assert(palindrome('never odd or even') === true); ``` -`palindrome("nope")` should return false. +`palindrome("nope")` 应该返回 `false`。 ```js assert(palindrome('nope') === false); ``` -`palindrome("almostomla")` should return false. +`palindrome("almostomla")` 应返回 `false`。 ```js assert(palindrome('almostomla') === false); ``` -`palindrome("My age is 0, 0 si ega ym.")` should return true. +`palindrome("My age is 0, 0 si ega ym.")` 应返回 `true`。 ```js assert(palindrome('My age is 0, 0 si ega ym.') === true); ``` -`palindrome("1 eye for of 1 eye.")` should return false. +`palindrome("1 eye for of 1 eye.")` 应返回 `false`。 ```js assert(palindrome('1 eye for of 1 eye.') === false); ``` -`palindrome("0_0 (: /-\ :) 0-0")` should return true. +`palindrome("0_0 (: /-\ :) 0-0")` 应返回 `true`。 ```js assert(palindrome('0_0 (: /- :) 0-0') === true); ``` -`palindrome("five|\_/|four")` should return false. +`palindrome("five|\_/|four")` 应返回 `false`。 ```js assert(palindrome('five|_/|four') === false); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/roman-numeral-converter.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/roman-numeral-converter.md index 9f750e7aed..ea66bf38eb 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/roman-numeral-converter.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/roman-numeral-converter.md @@ -1,6 +1,6 @@ --- id: a7f4d8f2483413a6ce226cac -title: Roman Numeral Converter +title: 罗马数字转换器 challengeType: 5 forumTopicId: 16044 dashedName: roman-numeral-converter @@ -8,163 +8,163 @@ dashedName: roman-numeral-converter # --description-- -Convert the given number into a roman numeral. +把传入的数字转为罗马数字。 -All [roman numerals](http://www.mathsisfun.com/roman-numerals.html) answers should be provided in upper-case. +转换后的[罗马数字](http://www.mathsisfun.com/roman-numerals.html)字母必须都是大写。 # --hints-- -`convertToRoman(2)` should return "II". +`convertToRoman(2)` 应该返回字符串 `II`。 ```js assert.deepEqual(convertToRoman(2), 'II'); ``` -`convertToRoman(3)` should return "III". +`convertToRoman(3)` 应该返回字符串 `III`。 ```js assert.deepEqual(convertToRoman(3), 'III'); ``` -`convertToRoman(4)` should return "IV". +`convertToRoman(4)` 应该返回字符串 `IV`。 ```js assert.deepEqual(convertToRoman(4), 'IV'); ``` -`convertToRoman(5)` should return "V". +`convertToRoman(5)` 应该返回字符串 `V`。 ```js assert.deepEqual(convertToRoman(5), 'V'); ``` -`convertToRoman(9)` should return "IX". +`convertToRoman(9)` 应该返回字符串 `IX`。 ```js assert.deepEqual(convertToRoman(9), 'IX'); ``` -`convertToRoman(12)` should return "XII". +`convertToRoman(12)` 应该返回字符串 `XII`。 ```js assert.deepEqual(convertToRoman(12), 'XII'); ``` -`convertToRoman(16)` should return "XVI". +`convertToRoman(16)` 应该返回字符串 `XVI`。 ```js assert.deepEqual(convertToRoman(16), 'XVI'); ``` -`convertToRoman(29)` should return "XXIX". +`convertToRoman(29)` 应该返回字符串 `XXIX`。 ```js assert.deepEqual(convertToRoman(29), 'XXIX'); ``` -`convertToRoman(44)` should return "XLIV". +`convertToRoman(44)` 应该返回字符串 `XLIV`. ```js assert.deepEqual(convertToRoman(44), 'XLIV'); ``` -`convertToRoman(45)` should return "XLV" +`convertToRoman(45)` 应该返回字符串 `XLV`。 ```js assert.deepEqual(convertToRoman(45), 'XLV'); ``` -`convertToRoman(68)` should return "LXVIII" +`convertToRoman(68)` 应该返回字符串 `LXVIII` ```js assert.deepEqual(convertToRoman(68), 'LXVIII'); ``` -`convertToRoman(83)` should return "LXXXIII" +`convertToRoman(83)` 应该返回字符串 `LXXXIII` ```js assert.deepEqual(convertToRoman(83), 'LXXXIII'); ``` -`convertToRoman(97)` should return "XCVII" +`convertToRoman(97)` 应该返回字符串 `XCVII` ```js assert.deepEqual(convertToRoman(97), 'XCVII'); ``` -`convertToRoman(99)` should return "XCIX" +`convertToRoman(99)` 应该返回字符串 `XCIX` ```js assert.deepEqual(convertToRoman(99), 'XCIX'); ``` -`convertToRoman(400)` should return "CD" +`convertToRoman(400)` 应该返回字符串 `CD` ```js assert.deepEqual(convertToRoman(400), 'CD'); ``` -`convertToRoman(500)` should return "D" +`convertToRoman(500)` 应该返回字符串 `D` ```js assert.deepEqual(convertToRoman(500), 'D'); ``` -`convertToRoman(501)` should return "DI" +`convertToRoman(501)` 应该返回字符串 `DI` ```js assert.deepEqual(convertToRoman(501), 'DI'); ``` -`convertToRoman(649)` should return "DCXLIX" +`convertToRoman(649)` 应该返回字符串 `DCXLIX` ```js assert.deepEqual(convertToRoman(649), 'DCXLIX'); ``` -`convertToRoman(798)` should return "DCCXCVIII" +`convertToRoman(798)` 应该返回字符串 `DCCXCVIII` ```js assert.deepEqual(convertToRoman(798), 'DCCXCVIII'); ``` -`convertToRoman(891)` should return "DCCCXCI" +`convertToRoman(891)` 应该返回字符串 `DCCCXCI` ```js assert.deepEqual(convertToRoman(891), 'DCCCXCI'); ``` -`convertToRoman(1000)` should return "M" +`convertToRoman(1000)` 应该返回字符串 `M` ```js assert.deepEqual(convertToRoman(1000), 'M'); ``` -`convertToRoman(1004)` should return "MIV" +`convertToRoman(1004)` 应该返回字符串 `MIV` ```js assert.deepEqual(convertToRoman(1004), 'MIV'); ``` -`convertToRoman(1006)` should return "MVI" +`convertToRoman(1006)` 应该返回字符串 `MVI` ```js assert.deepEqual(convertToRoman(1006), 'MVI'); ``` -`convertToRoman(1023)` should return "MXXIII" +`convertToRoman(1023)` 应该返回字符串 `MXXIII` ```js assert.deepEqual(convertToRoman(1023), 'MXXIII'); ``` -`convertToRoman(2014)` should return "MMXIV" +`convertToRoman(2014)` 应该返回字符串 `MMXIV` ```js assert.deepEqual(convertToRoman(2014), 'MMXIV'); ``` -`convertToRoman(3999)` should return "MMMCMXCIX" +`convertToRoman(3999)` 应该返回字符串 `MMMCMXCIX` ```js assert.deepEqual(convertToRoman(3999), 'MMMCMXCIX'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator.md index 67d1515d0f..b3f2306938 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator.md @@ -1,6 +1,6 @@ --- id: aff0395860f5d3034dc0bfc9 -title: Telephone Number Validator +title: 电话号码检查器 challengeType: 5 forumTopicId: 16090 dashedName: telephone-number-validator @@ -8,173 +8,173 @@ dashedName: telephone-number-validator # --description-- -Return `true` if the passed string looks like a valid US phone number. +如果传入的字符串是一个有效的美国电话号码格式,则返回 `true`。 -The user may fill out the form field any way they choose as long as it has the format of a valid US number. The following are examples of valid formats for US numbers (refer to the tests below for other variants): +只要是有效的美国电话号码的格式,用户可以按照他们的方式填写表单中的电话号码。 以下是一些正确的例子(其他格式变形请参考以下例子): -

555-555-5555
(555)555-5555
(555) 555-5555
555 555 5555
5555555555
1 555 555 5555
+
555-555-5555
(555)555-5555
(555)555-5555
555 555 5555
5555555555
1 555 555 5555
-For this challenge you will be presented with a string such as `800-692-7753` or `8oo-six427676;laskdjf`. Your job is to validate or reject the US phone number based on any combination of the formats provided above. The area code is required. If the country code is provided, you must confirm that the country code is `1`. Return `true` if the string is a valid US phone number; otherwise return `false`. +在这个挑战中,参数可能是 `800-692-7753` 或者 `8oo-six427676;laskdjf` 的号码。 你的任务是根据上面不同的格式组合,判断它是否为有效的电话号码。 其中,地区码(电话号码中的前三位)是必须的。 如果提供国家代码,则国家代码只能为 `1`。 如果传入的参数是有效的美国电话号码就返回 `true`,否则返回 `false`。 # --hints-- -`telephoneCheck("555-555-5555")` should return a boolean. +`telephoneCheck("555-555-5555")` 应返回一个布尔值。 ```js assert(typeof telephoneCheck('555-555-5555') === 'boolean'); ``` -`telephoneCheck("1 555-555-5555")` should return true. +`telephoneCheck("1 555-555-5555")` 应返回 `true`。 ```js assert(telephoneCheck('1 555-555-5555') === true); ``` -`telephoneCheck("1 (555) 555-5555")` should return true. +`telephoneCheck("1 (555) 555-5555")` 应返回 `true`。 ```js assert(telephoneCheck('1 (555) 555-5555') === true); ``` -`telephoneCheck("5555555555")` should return true. +`telephoneCheck("5555555555")` 应返回 `true`。 ```js assert(telephoneCheck('5555555555') === true); ``` -`telephoneCheck("555-555-5555")` should return true. +`telephoneCheck("555-555-5555")` 应返回 `true`。 ```js assert(telephoneCheck('555-555-5555') === true); ``` -`telephoneCheck("(555)555-5555")` should return true. +`telephoneCheck("(555)555-5555")` 应返回 `true`。 ```js assert(telephoneCheck('(555)555-5555') === true); ``` -`telephoneCheck("1(555)555-5555")` should return true. +`telephoneCheck("1(555)555-5555")` 应返回 `true`。 ```js assert(telephoneCheck('1(555)555-5555') === true); ``` -`telephoneCheck("555-5555")` should return false. +`telephoneCheck("555-5555")` 应返回 `false`。 ```js assert(telephoneCheck('555-5555') === false); ``` -`telephoneCheck("5555555")` should return false. +`telephoneCheck("5555555")` 应返回 `false`。 ```js assert(telephoneCheck('5555555') === false); ``` -`telephoneCheck("1 555)555-5555")` should return false. +`telephoneCheck("1 555)555-5555")` 应返回 `false`。 ```js assert(telephoneCheck('1 555)555-5555') === false); ``` -`telephoneCheck("1 555 555 5555")` should return true. +`telephoneCheck("1 555 555 5555")` 应返回 `true`。 ```js assert(telephoneCheck('1 555 555 5555') === true); ``` -`telephoneCheck("1 456 789 4444")` should return true. +`telephoneCheck("1 456 789 4444")` 应返回 `true`。 ```js assert(telephoneCheck('1 456 789 4444') === true); ``` -`telephoneCheck("123**&!!asdf#")` should return false. +`telephoneCheck("123**&!!asdf#")` 应返回 `false`。 ```js assert(telephoneCheck('123**&!!asdf#') === false); ``` -`telephoneCheck("55555555")` should return false. +`telephoneCheck("55555555")` 应返回 `false`。 ```js assert(telephoneCheck('55555555') === false); ``` -`telephoneCheck("(6054756961)")` should return false +`telephoneCheck("(6054756961)")` 应返回 `false`。 ```js assert(telephoneCheck('(6054756961)') === false); ``` -`telephoneCheck("2 (757) 622-7382")` should return false. +`telephoneCheck("2 (757) 622-7382")` 应返回 `false`。 ```js assert(telephoneCheck('2 (757) 622-7382') === false); ``` -`telephoneCheck("0 (757) 622-7382")` should return false. +`telephoneCheck("0 (757) 622-7382")` 应返回 `false`。 ```js assert(telephoneCheck('0 (757) 622-7382') === false); ``` -`telephoneCheck("-1 (757) 622-7382")` should return false +`telephoneCheck("-1 (757) 622-7382")` 应返回 `false`。 ```js assert(telephoneCheck('-1 (757) 622-7382') === false); ``` -`telephoneCheck("2 757 622-7382")` should return false. +`telephoneCheck("2 757 622-7382")` 应返回 `false`。 ```js assert(telephoneCheck('2 757 622-7382') === false); ``` -`telephoneCheck("10 (757) 622-7382")` should return false. +`telephoneCheck("10 (757) 622-7382")` 应返回 `false`。 ```js assert(telephoneCheck('10 (757) 622-7382') === false); ``` -`telephoneCheck("27576227382")` should return false. +`telephoneCheck("27576227382")` 应返回 `false`。 ```js assert(telephoneCheck('27576227382') === false); ``` -`telephoneCheck("(275)76227382")` should return false. +`telephoneCheck("(275)76227382")` 应返回 `false`。 ```js assert(telephoneCheck('(275)76227382') === false); ``` -`telephoneCheck("2(757)6227382")` should return false. +`telephoneCheck("2(757)6227382")` 应返回 `false`。 ```js assert(telephoneCheck('2(757)6227382') === false); ``` -`telephoneCheck("2(757)622-7382")` should return false. +`telephoneCheck("2(757)622-7382")` 应返回 `false`。 ```js assert(telephoneCheck('2(757)622-7382') === false); ``` -`telephoneCheck("555)-555-5555")` should return false. +`telephoneCheck("555)-555-5555")` 应返回 `false`。 ```js assert(telephoneCheck('555)-555-5555') === false); ``` -`telephoneCheck("(555-555-5555")` should return false. +`telephoneCheck("(555-555-5555")` 应返回 `false`。 ```js assert(telephoneCheck('(555-555-5555') === false); ``` -`telephoneCheck("(555)5(55?)-5555")` should return false. +`telephoneCheck("(555)5(55?)-5555")` 应返回 `false`。 ```js assert(telephoneCheck('(555)5(55?)-5555') === false); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/add-methods-after-inheritance.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/add-methods-after-inheritance.md index 4475a902b1..843ee1f55a 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/add-methods-after-inheritance.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/add-methods-after-inheritance.md @@ -1,6 +1,6 @@ --- id: 587d7db1367417b2b2512b87 -title: Add Methods After Inheritance +title: 继承后添加方法 challengeType: 1 forumTopicId: 301315 dashedName: add-methods-after-inheritance @@ -8,9 +8,9 @@ dashedName: add-methods-after-inheritance # --description-- -A constructor function that inherits its `prototype` object from a supertype constructor function can still have its own methods in addition to inherited methods. +从超类构造函数继承其 `prototype` 对象的构造函数,除了继承的方法外,还可以拥有自己的方法。 -For example, `Bird` is a constructor that inherits its `prototype` from `Animal`: +请看举例:`Bird` 是一个构造函数,它继承了 `Animal` 的 `prototype`: ```js function Animal() { } @@ -22,7 +22,7 @@ Bird.prototype = Object.create(Animal.prototype); Bird.prototype.constructor = Bird; ``` -In addition to what is inherited from `Animal`, you want to add behavior that is unique to `Bird` objects. Here, `Bird` will get a `fly()` function. Functions are added to `Bird's` `prototype` the same way as any constructor function: +除了从 `Animal` 构造函数继承的行为之外,还需要给 `Bird` 对象添加它独有的行为。 这里,我们给 `Bird` 对象添加一个 `fly()` 函数。 函数会以一种与其他构造函数相同的方式添加到 `Bird's` 的 `prototype` 中: ```js Bird.prototype.fly = function() { @@ -30,51 +30,53 @@ Bird.prototype.fly = function() { }; ``` -Now instances of `Bird` will have both `eat()` and `fly()` methods: +现在 `Bird` 的实例中就有了 `eat()` 和 `fly()` 这两个方法: ```js let duck = new Bird(); -duck.eat(); // prints "nom nom nom" -duck.fly(); // prints "I'm flying!" +duck.eat(); +duck.fly(); ``` +`duck.eat()` 将在控制台中显示字符串 `nom nom nom`, `duck.fly()` 将显示字符串 `I'm flying!`。 + # --instructions-- -Add all necessary code so the `Dog` object inherits from `Animal` and the `Dog's` `prototype` constructor is set to Dog. Then add a `bark()` method to the `Dog` object so that `beagle` can both `eat()` and `bark()`. The `bark()` method should print "Woof!" to the console. +添加必要的代码,使得 `Dog` 对象继承 `Animal`,并且把 `Dog` 的 `prototype`上的 constructor 属性设置为 `Dog`。 然后给 `Dog` 对象添加一个 `bark()` 方法,这样的话,`beagle` 将同时拥有 `eat()` 和 `bark()` 这两个方法。 `bark()` 方法中应该输出 `Woof!` 到控制台。 # --hints-- -`Animal` should not respond to the `bark()` method. +`Animal` 应该没有 `bark()` 方法。 ```js assert(typeof Animal.prototype.bark == 'undefined'); ``` -`Dog` should inherit the `eat()` method from `Animal`. +`Dog` 应该继承了 `Animal` 的 `eat()` 方法。 ```js assert(typeof Dog.prototype.eat == 'function'); ``` -`Dog` should have the `bark()` method as an `own` property. +`Dog` 应该有一个 `bark()` 方法作为 `own` 属性。 ```js assert(Dog.prototype.hasOwnProperty('bark')); ``` -`beagle` should be an `instanceof` `Animal`. +`beagle` 应该是 `Animal` 的一个 `instanceof`。 ```js assert(beagle instanceof Animal); ``` -The constructor for `beagle` should be set to `Dog`. +`beagle` 的 constructor 属性应该被设置为 `Dog`。 ```js assert(beagle.constructor === Dog); ``` -`beagle.eat()` should log `"nom nom nom"` +`beagle.eat()` 应该记录字符串 `nom nom nom` ```js console.log = function (msg) { @@ -83,7 +85,7 @@ console.log = function (msg) { assert.throws(() => beagle.eat(), 'nom nom nom'); ``` -`beagle.bark()` should log `"Woof!"` +`beagle.bark()` 应该将字符串 `Woof!` 打印到控制台 ```js console.log = function (msg) { diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/change-the-prototype-to-a-new-object.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/change-the-prototype-to-a-new-object.md index 5313994f24..7503c3edcc 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/change-the-prototype-to-a-new-object.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/change-the-prototype-to-a-new-object.md @@ -1,6 +1,6 @@ --- id: 587d7daf367417b2b2512b7f -title: Change the Prototype to a New Object +title: 将原型更改为新对象 challengeType: 1 forumTopicId: 301316 dashedName: change-the-prototype-to-a-new-object @@ -8,13 +8,13 @@ dashedName: change-the-prototype-to-a-new-object # --description-- -Up until now you have been adding properties to the `prototype` individually: +到目前为止,你已经可以单独给 `prototype` 添加属性了: ```js Bird.prototype.numLegs = 2; ``` -This becomes tedious after more than a few properties. +需要添加多个属性的,这未免会显得拖沓。 ```js Bird.prototype.eat = function() { @@ -26,7 +26,7 @@ Bird.prototype.describe = function() { } ``` -A more efficient way is to set the `prototype` to a new object that already contains the properties. This way, the properties are added all at once: +一种更有效的方法就是给对象的 `prototype` 设置为一个已经包含了属性的新对象。 这样一来,所有属性都可以一次性添加进来: ```js Bird.prototype = { @@ -42,29 +42,29 @@ Bird.prototype = { # --instructions-- -Add the property `numLegs` and the two methods `eat()` and `describe()` to the `prototype` of `Dog` by setting the `prototype` to a new object. +通过给 `prototype` 设置一个对象,在 `Dog` 构造函数的 `prototype` 上添加一个属性 `numLegs` 以及两个方法:`eat()` 和 `describe()`。 # --hints-- -`Dog.prototype` should be set to a new object. +`Dog.prototype` 应该被设置为一个新对象。 ```js assert(/Dog\.prototype\s*?=\s*?{/.test(code)); ``` -`Dog.prototype` should have the property `numLegs`. +`Dog.prototype` 应该拥有属性 `numLegs`。 ```js assert(Dog.prototype.numLegs !== undefined); ``` -`Dog.prototype` should have the method `eat()`. +`Dog.prototype` 应该拥有方法 `eat()`。 ```js assert(typeof Dog.prototype.eat === 'function'); ``` -`Dog.prototype` should have the method `describe()`. +`Dog.prototype` 应该拥有方法 `describe()`。 ```js assert(typeof Dog.prototype.describe === 'function'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/create-a-basic-javascript-object.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/create-a-basic-javascript-object.md index c71fb6cd85..5b0af9df1b 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/create-a-basic-javascript-object.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/create-a-basic-javascript-object.md @@ -1,6 +1,6 @@ --- id: 587d7dac367417b2b2512b73 -title: Create a Basic JavaScript Object +title: 创建一个基本的 JavaScript 对象 challengeType: 1 forumTopicId: 301317 dashedName: create-a-basic-javascript-object @@ -8,13 +8,13 @@ dashedName: create-a-basic-javascript-object # --description-- -Think about things people see every day, like cars, shops, and birds. These are all objects: tangible things people can observe and interact with. +想想我们在生活中每天都可见到的事物:比如汽车、商店以及小鸟等。 它们都是对象:即人们可以观察和与之互动的实体事物。 -What are some qualities of these objects? A car has wheels. Shops sell items. Birds have wings. +这些物体的性质是什么? 汽车有轮子。 商店销售物品。 鸟儿有翅膀。 -These qualities, or properties, define what makes up an object. Note that similar objects share the same properties, but may have different values for those properties. For example, all cars have wheels, but not all cars have the same number of wheels. +这些特征,或者说是属性定义了一个对象由什么构成的。 需要注意的是:那些相似的对象可以拥有相同的属性,但是这些属性可能会有不同的值。 举个例子:所有的汽车都有轮子,但并不是所有汽车的轮子个数都是一样的。 -Objects in JavaScript are used to model real-world objects, giving them properties and behavior just like their real-world counterparts. Here's an example using these concepts to create a `duck` object: +JavaScript 中的对象可以用来描述现实世界中的物体,并赋予他们属性和行为,就像它们在现实世界中的对应物一样。 下面是使用这些概念来创建一个 `duck` 对象的示例: ```js let duck = { @@ -23,27 +23,27 @@ let duck = { }; ``` -This `duck` object has two property/value pairs: a `name` of "Aflac" and a `numLegs` of 2. +这个 `duck` 对象有两组键值对:一个是 `name` 属性,它的值是 `Aflac`;另一个是 `numLegs` 属性,它的值是 2。 # --instructions-- -Create a `dog` object with `name` and `numLegs` properties, and set them to a string and a number, respectively. +创建一个 `dog` 对象,并给这个对象添加两个属性:`name` 和 `numLegs`,同时把这两个属性的值分别设为字符串和数字。 # --hints-- -`dog` should be an object. +`dog` 应该是一个 object。 ```js assert(typeof dog === 'object'); ``` -`dog` should have a `name` property set to a `string`. +`dog` 应该有一个 `name` 属性且它的值是一个字符串。 ```js assert(typeof dog.name === 'string'); ``` -`dog` should have a `numLegs` property set to a `number`. +`dog` 应该有一个 `numLegs` 属性且它的值是一个数字。 ```js assert(typeof dog.numLegs === 'number'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/create-a-method-on-an-object.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/create-a-method-on-an-object.md index 0399c52c15..c60481ab0b 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/create-a-method-on-an-object.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/create-a-method-on-an-object.md @@ -1,6 +1,6 @@ --- id: 587d7dad367417b2b2512b75 -title: Create a Method on an Object +title: 在对象上创建方法 challengeType: 1 forumTopicId: 301318 dashedName: create-a-method-on-an-object @@ -8,9 +8,9 @@ dashedName: create-a-method-on-an-object # --description-- -Objects can have a special type of property, called a method. +对象可以有一个叫做 method 的特殊属性。 -Methods are properties that are functions. This adds different behavior to an object. Here is the `duck` example with a method: +方法属性也就是函数。 这给对象添加了不同的行为。 以下就是一个带有方法属性的 `duck` 示例: ```js let duck = { @@ -19,24 +19,23 @@ let duck = { sayName: function() {return "The name of this duck is " + duck.name + ".";} }; duck.sayName(); -// Returns "The name of this duck is Aflac." ``` -The example adds the `sayName` method, which is a function that returns a sentence giving the name of the `duck`. Notice that the method accessed the `name` property in the return statement using `duck.name`. The next challenge will cover another way to do this. +示例添加了 `sayName` 方法,函数返回包含 `duck` 名字的一个句子。 注意:这个方法在返回语句中使用 `duck.name` 的方式来获取 `name` 的属性值。 在下一个挑战中我们将会使用另外一种方法来实现。 # --instructions-- -Using the `dog` object, give it a method called `sayLegs`. The method should return the sentence "This dog has 4 legs." +给 `dog` 对象设置一个名为 `sayLegs` 的方法。 并让它返回 `This dog has 4 legs.` 这句话。 # --hints-- -`dog.sayLegs()` should be a function. +`dog.sayLegs()` 应该是一个函数。 ```js assert(typeof dog.sayLegs === 'function'); ``` -`dog.sayLegs()` should return the given string - note that punctuation and spacing matter. +`dog.sayLegs()` 应该返回给定的字符串,需要注意标点和间距的问题。 ```js assert(dog.sayLegs() === 'This dog has 4 legs.'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/define-a-constructor-function.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/define-a-constructor-function.md index ffc215f1f6..bc6e6a2590 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/define-a-constructor-function.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/define-a-constructor-function.md @@ -1,6 +1,6 @@ --- id: 587d7dad367417b2b2512b77 -title: Define a Constructor Function +title: 定义构造函数 challengeType: 1 forumTopicId: 16804 dashedName: define-a-constructor-function @@ -8,9 +8,9 @@ dashedName: define-a-constructor-function # --description-- -Constructors are functions that create new objects. They define properties and behaviors that will belong to the new object. Think of them as a blueprint for the creation of new objects. +Constructors 是创建对象的函数。 函数给这个新对象定义属性和行为。 可将它们视为创建的新对象的蓝图。 -Here is an example of a constructor: +以下就是一个构造函数的示例: ```js function Bird() { @@ -20,29 +20,29 @@ function Bird() { } ``` -This constructor defines a `Bird` object with properties `name`, `color`, and `numLegs` set to Albert, blue, and 2, respectively. Constructors follow a few conventions: +这个构造函数定义了一个 `Bird` 对象,其属性 `name`、`color` 和 `numLegs` 的值分别被设置为 Albert、blue 和 2。 构造函数遵循一些惯例规则: - + # --instructions-- -Create a constructor, `Dog`, with properties `name`, `color`, and `numLegs` that are set to a string, a string, and a number, respectively. +创建一个构造函数:`Dog`。 给其添加 `name`,`color` 和 `numLegs` 属性并分别给它们设置为:字符串、字符串和数字。 # --hints-- -`Dog` should have a `name` property set to a string. +`Dog` 应该有一个 `name` 属性且它的值是一个字符串。 ```js assert(typeof new Dog().name === 'string'); ``` -`Dog` should have a `color` property set to a string. +`Dog` 应该有一个 `color` 属性且它的值是一个字符串。 ```js assert(typeof new Dog().color === 'string'); ``` -`Dog` should have a `numLegs` property set to a number. +`Dog` 应该有一个 `numLegs` 属性且它的值是一个数字。 ```js assert(typeof new Dog().numLegs === 'number'); @@ -51,7 +51,9 @@ assert(typeof new Dog().numLegs === 'number'); # --seed-- ## --seed-contents-- + ```js + ``` # --solutions-- diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/extend-constructors-to-receive-arguments.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/extend-constructors-to-receive-arguments.md index 99a679937a..6b32538b8e 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/extend-constructors-to-receive-arguments.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/extend-constructors-to-receive-arguments.md @@ -1,6 +1,6 @@ --- id: 587d7dae367417b2b2512b79 -title: Extend Constructors to Receive Arguments +title: 扩展构造函数以接收参数 challengeType: 1 forumTopicId: 18235 dashedName: extend-constructors-to-receive-arguments @@ -8,7 +8,7 @@ dashedName: extend-constructors-to-receive-arguments # --description-- -The `Bird` and `Dog` constructors from last challenge worked well. However, notice that all `Birds` that are created with the `Bird` constructor are automatically named Albert, are blue in color, and have two legs. What if you want birds with different values for name and color? It's possible to change the properties of each bird manually but that would be a lot of work: +上一个挑战中 `Bird` 和 `Dog` 构造函数运行得不错。 但是,注意到没有:所有通过`Bird` 构造函数创建出来的实例 `Birds` 都自动的取名为 Albert,颜色都是蓝色,还都有两条腿。 如果你想要新创建出来的小鸟们拥有不同的名字和颜色要怎么办呢? 当然,手动的去修改每一个小鸟实例自己的属性也是可以实现的,只是会增加很多无谓的工作量: ```js let swan = new Bird(); @@ -16,7 +16,7 @@ swan.name = "Carlos"; swan.color = "white"; ``` -Suppose you were writing a program to keep track of hundreds or even thousands of different birds in an aviary. It would take a lot of time to create all the birds, then change the properties to different values for every one. To more easily create different `Bird` objects, you can design your Bird constructor to accept parameters: +假如你写了一个程序来追踪一个鸟舍里面的几百只甚至几千只不同的小鸟。 你将会花费很多时间去创建所有的小鸟实例并给它们的属性一一修改为不同的值。 为了减轻创建不同 `Bird` 对象的工作量,你可以给你的 Bird 设置为可以接收参数的构造函数: ```js function Bird(name, color) { @@ -26,41 +26,41 @@ function Bird(name, color) { } ``` -Then pass in the values as arguments to define each unique bird into the `Bird` constructor: `let cardinal = new Bird("Bruce", "red");` This gives a new instance of `Bird` with name and color properties set to Bruce and red, respectively. The `numLegs` property is still set to 2. The `cardinal` has these properties: +然后将值通过参数的方式传递给 `Bird` 构造函数来定义每一个唯一的小鸟实例: `let cardinal = new Bird("Bruce", "red");` 这给 `Bird` 的 `name` 和 `color` 属性分别赋值为 `Bruce` 和 `red` 色。 但 `numLegs` 属性仍然设置为 2。 `cardinal` 有以下这些属性: ```js -cardinal.name // => Bruce -cardinal.color // => red -cardinal.numLegs // => 2 +cardinal.name +cardinal.color +cardinal.numLegs ``` -The constructor is more flexible. It's now possible to define the properties for each `Bird` at the time it is created, which is one way that JavaScript constructors are so useful. They group objects together based on shared characteristics and behavior and define a blueprint that automates their creation. +这样一来构造函数就变得很灵活了。 现在可以在创建每个`Bird`实例时直接定义属性,这是 JavaScript 构造函数非常实用的用法之一。 它们根据共同或相似的属性和行为将对象归纳为一组,并能够自动的创建各自实例。 # --instructions-- -Create another `Dog` constructor. This time, set it up to take the parameters `name` and `color`, and have the property `numLegs` fixed at 4. Then create a new `Dog` saved in a variable `terrier`. Pass it two strings as arguments for the `name` and `color` properties. +创建另一个 `Dog` 构造函数。 这一次,给它设置两个参数:`name` 和 `color`,同时给 `numLegs` 赋值为 4。 然后创建一个新 `Dog` 实例保存为变量名:`terrier`。 再将两个字符串通过参数的形式传入`name` 和 `color` 属性。 # --hints-- -`Dog` should receive an argument for `name`. +`Dog` 应该接收一个 `name` 参数。 ```js assert(new Dog('Clifford').name === 'Clifford'); ``` -`Dog` should receive an argument for `color`. +`Dog` 应该接收一个 `color` 参数。 ```js assert(new Dog('Clifford', 'yellow').color === 'yellow'); ``` -`Dog` should have property `numLegs` set to 4. +`Dog` 应该有一个 `numLegs` 属性且值为 4。 ```js assert(new Dog('Clifford').numLegs === 4); ``` -`terrier` should be created using the `Dog` constructor. +`terrier` 应该是通过 `Dog` 构造函数创建的。 ```js assert(terrier instanceof Dog); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/inherit-behaviors-from-a-supertype.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/inherit-behaviors-from-a-supertype.md index 357fdeab57..5b350e0b55 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/inherit-behaviors-from-a-supertype.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/inherit-behaviors-from-a-supertype.md @@ -1,6 +1,6 @@ --- id: 587d7db0367417b2b2512b84 -title: Inherit Behaviors from a Supertype +title: 从超类继承行为 challengeType: 1 forumTopicId: 301319 dashedName: inherit-behaviors-from-a-supertype @@ -8,7 +8,7 @@ dashedName: inherit-behaviors-from-a-supertype # --description-- -In the previous challenge, you created a `supertype` called `Animal` that defined behaviors shared by all animals: +在上一个挑战中,我们创建了一个`Animal` 超类(`supertype`),用来定义所有动物共有的行为: ```js function Animal() { } @@ -17,44 +17,46 @@ Animal.prototype.eat = function() { }; ``` -This and the next challenge will cover how to reuse `Animal's` methods inside `Bird` and `Dog` without defining them again. It uses a technique called inheritance. This challenge covers the first step: make an instance of the `supertype` (or parent). You already know one way to create an instance of `Animal` using the `new` operator: +在这一节以及下一节挑战中我们将学习如何在 `Bird` 和 `Dog` 中重用 `Animal's` 中的方法,而无需重新定义它们。 这里我们会用到构造函数的继承特性。 这一节挑战中我们学习第一步:创建一个超类 `supertype`(或者叫父类)的实例。 你已经学会了一种创建 `Animal` 实例的方法,即使用 `new` 操作符: ```js let animal = new Animal(); ``` -There are some disadvantages when using this syntax for inheritance, which are too complex for the scope of this challenge. Instead, here's an alternative approach without those disadvantages: +此语法用于继承时会存在一些缺点,这些缺点对于当前我们这个挑战来说太复杂了。 相反,我们学习另外一种没有这些缺点的方法来替代 new 操作: ```js let animal = Object.create(Animal.prototype); ``` -`Object.create(obj)` creates a new object, and sets `obj` as the new object's `prototype`. Recall that the `prototype` is like the "recipe" for creating an object. By setting the `prototype` of `animal` to be `Animal's` `prototype`, you are effectively giving the `animal` instance the same "recipe" as any other instance of `Animal`. +`Object.create(obj)` 创建了一个新对象,并指定了 `obj` 作为新对象的 `prototype`。 回忆一下,我们之前说过 `prototype` 就像是创建对象的“配方”。 如果我们把 `animal` 的 `prototype` 设置为与 `Animal's` 构造函数的 `prototype` 一样,那么就相当于让 `animal` 这个实例的配方与 `Animal` 其他实例的配方一样了。 ```js -animal.eat(); // prints "nom nom nom" -animal instanceof Animal; // => true +animal.eat(); +animal instanceof Animal; ``` +`instanceof` 方法会返回 `true`. + # --instructions-- -Use `Object.create` to make two instances of `Animal` named `duck` and `beagle`. +使用 `Object.create` 方法给 `Animal` 创建两个实例:`duck` 和 `beagle`。 # --hints-- -The `duck` variable should be defined. +应该定义一个 `duck` 变量。 ```js assert(typeof duck !== 'undefined'); ``` -The `beagle` variable should be defined. +应该定义一个 `beagle` 变量。 ```js assert(typeof beagle !== 'undefined'); ``` -The `duck` variable should be initialised with `Object.create`. +`duck` 变量应该通过 `Object.create` 初始化。 ```js assert( @@ -64,7 +66,7 @@ assert( ); ``` -The `beagle` variable should be initialised with `Object.create`. +`beagle` 变量应该通过 `Object.create` 初始化。 ```js assert( @@ -74,13 +76,13 @@ assert( ); ``` -`duck` should have a `prototype` of `Animal`. +`duck` 的原型应该被设置为 `Animal` 的 `prototype`。 ```js assert(duck instanceof Animal); ``` -`beagle` should have a `prototype` of `Animal`. +`beagle` 的 `prototype` 应该是 `Animal`。 ```js assert(beagle instanceof Animal); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/iterate-over-all-properties.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/iterate-over-all-properties.md index bc6aa77d26..3b39659ff4 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/iterate-over-all-properties.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/iterate-over-all-properties.md @@ -1,6 +1,6 @@ --- id: 587d7daf367417b2b2512b7d -title: Iterate Over All Properties +title: 迭代所有属性 challengeType: 1 forumTopicId: 301320 dashedName: iterate-over-all-properties @@ -8,7 +8,7 @@ dashedName: iterate-over-all-properties # --description-- -You have now seen two kinds of properties: `own` properties and `prototype` properties. `Own` properties are defined directly on the object instance itself. And `prototype` properties are defined on the `prototype`. +现在你已经了解了两种属性: `own` 属性和 `prototype` 属性。 `Own` 属性是直接在对象上定义的。 而 `prototype` 属性是定义在 `prototype` 上的。 ```js function Bird(name) { @@ -20,7 +20,7 @@ Bird.prototype.numLegs = 2; // prototype property let duck = new Bird("Donald"); ``` -Here is how you add `duck`'s `own` properties to the array `ownProps` and `prototype` properties to the array `prototypeProps`: +这个示例会告诉你如何将 `duck` 的 `own` 属性和 `prototype` 属性分别添加到 `ownProps` 数组和 `prototypeProps` 数组里面: ```js let ownProps = []; @@ -34,29 +34,31 @@ for (let property in duck) { } } -console.log(ownProps); // prints ["name"] -console.log(prototypeProps); // prints ["numLegs"] +console.log(ownProps); +console.log(prototypeProps); ``` +`console.log(ownProps)` 将在控制台中显示 `["name"]` ,`console.log(prototypeProps)` 将显示 `["numLegs"]`。 + # --instructions-- -Add all of the `own` properties of `beagle` to the array `ownProps`. Add all of the `prototype` properties of `Dog` to the array `prototypeProps`. +将 `beagle` 的 `own` 属性都添加到 `ownProps` 数组里面去。 将 `Dog` 中所有的 `prototype` 属性都添加到 `prototypeProps` 数组中。 # --hints-- -The `ownProps` array should only contain `"name"`. +`ownProps` 数组应该包含 `name`。 ```js assert.deepEqual(ownProps, ['name']); ``` -The `prototypeProps` array should only contain `"numLegs"`. +`prototypeProps` 数组应该包含 `numLegs`。 ```js assert.deepEqual(prototypeProps, ['numLegs']); ``` -You should solve this challenge without using the built in method `Object.keys()`. +在不使用内置方法 `Object.keys()` 的前提下完成这个挑战。 ```js assert(!/\Object.keys/.test(code)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/make-code-more-reusable-with-the-this-keyword.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/make-code-more-reusable-with-the-this-keyword.md index fc3324f479..834082d299 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/make-code-more-reusable-with-the-this-keyword.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/make-code-more-reusable-with-the-this-keyword.md @@ -1,6 +1,6 @@ --- id: 587d7dad367417b2b2512b76 -title: Make Code More Reusable with the this Keyword +title: 使用 this 关键字提高代码重用性 challengeType: 1 forumTopicId: 301321 dashedName: make-code-more-reusable-with-the-this-keyword @@ -8,13 +8,13 @@ dashedName: make-code-more-reusable-with-the-this-keyword # --description-- -The last challenge introduced a method to the `duck` object. It used `duck.name` dot notation to access the value for the `name` property within the return statement: +在上一个挑战中我们了解了该如何给 `duck` 对象设置一个方法。 然后在 return 语句里,我们通过使用 “点号表示法” `duck.name` 来获取 `name` 的属性值: `sayName: function() {return "The name of this duck is " + duck.name + ".";}` -While this is a valid way to access the object's property, there is a pitfall here. If the variable name changes, any code referencing the original name would need to be updated as well. In a short object definition, it isn't a problem, but if an object has many references to its properties there is a greater chance for error. +虽然这是访问对象属性的有效方法,但是这里有一个陷阱。 如果变量名发生了改变,那么引用了原始名称的任何代码都需要更新。 在一个简短的对象定义中这并不是问题,但是如果对象有很多对其属性的引用,那么发生错误的可能性就更大了。 -A way to avoid these issues is with the `this` keyword: +我们可以使用 `this` 关键字来避免这一问题: ```js let duck = { @@ -24,21 +24,21 @@ let duck = { }; ``` -`this` is a deep topic, and the above example is only one way to use it. In the current context, `this` refers to the object that the method is associated with: `duck`. If the object's name is changed to `mallard`, it is not necessary to find all the references to `duck` in the code. It makes the code reusable and easier to read. +`this` 是一个很复杂的知识点,而上面那个例子也只是使用 this 的一种方法而已。 在当前的上下文环境中,`this` 指向的就是与这个方法有关联的 `duck` 对象。 如果把对象的变量名改为 `mallard`,那使用 this 就没有必要在代码中找到所有指向 `duck` 的部分。 这样可以使得代码更具有可读性和复用性。 # --instructions-- -Modify the `dog.sayLegs` method to remove any references to `dog`. Use the `duck` example for guidance. +修改 `dog.sayLegs` 方法以将所有直接对 `dog` 的引用删除。 可以参考上面 `duck` 的例子。 # --hints-- -`dog.sayLegs()` should return the given string. +`dog.sayLegs()` 应该返回一个指定的字符串。 ```js assert(dog.sayLegs() === 'This dog has 4 legs.'); ``` -Your code should use the `this` keyword to access the `numLegs` property of `dog`. +你的代码应该使用 `this` 关键字来访问 `dog` 对象的 `numLegs` 属性值。 ```js assert(code.match(/this\.numLegs/g)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/override-inherited-methods.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/override-inherited-methods.md index 24ee9ad513..ea7eb3cedc 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/override-inherited-methods.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/override-inherited-methods.md @@ -1,6 +1,6 @@ --- id: 587d7db1367417b2b2512b88 -title: Override Inherited Methods +title: 重写继承的方法 challengeType: 1 forumTopicId: 301322 dashedName: override-inherited-methods @@ -8,19 +8,19 @@ dashedName: override-inherited-methods # --description-- -In previous lessons, you learned that an object can inherit its behavior (methods) from another object by referencing its `prototype` object: +在上一个挑战中,我们学习了一个对象可以通过引用另一个对象的 `prototype` 来继承其属性和行为(或方法): ```js ChildObject.prototype = Object.create(ParentObject.prototype); ``` -Then the `ChildObject` received its own methods by chaining them onto its `prototype`: +然后,`ChildObject` 将自己的方法链接到它的 `prototype`中: ```js ChildObject.prototype.methodName = function() {...}; ``` -It's possible to override an inherited method. It's done the same way - by adding a method to `ChildObject.prototype` using the same method name as the one to override. Here's an example of `Bird` overriding the `eat()` method inherited from `Animal`: +我们还可以重写继承的方法。 以同样的方式 - 通过使用一个与需要重写的方法相同的方法名,向`ChildObject.prototype` 中添加方法。 请看下面的举例:`Bird` 重写了从 `Animal` 继承来的 `eat()` 方法: ```js function Animal() { } @@ -29,35 +29,33 @@ Animal.prototype.eat = function() { }; function Bird() { } -// Inherit all methods from Animal Bird.prototype = Object.create(Animal.prototype); -// Bird.eat() overrides Animal.eat() Bird.prototype.eat = function() { return "peck peck peck"; }; ``` -If you have an instance `let duck = new Bird();` and you call `duck.eat()`, this is how JavaScript looks for the method on `duck’s` `prototype` chain: +如果你有一个实例:`let duck = new Bird();`,然后你调用了 `duck.eat()`,以下就是 JavaScript 在 `duck’s` 的 `prototype` 链上寻找方法的过程: -1. duck => Is eat() defined here? No. -2. Bird => Is eat() defined here? => Yes. Execute it and stop searching. -3. Animal => eat() is also defined, but JavaScript stopped searching before reaching this level. -4. Object => JavaScript stopped searching before reaching this level. +1. `duck` => `eat()` 是定义在这里吗? 不是。 +2. `Bird` => `eat()` 是定义在这里吗? => 是的。 执行它并停止往上搜索。 +3. `Animal` => 这里也定义了 `eat()` 方法,但是 JavaScript 在到达这层原型链之前已停止了搜索。 +4. Object => JavaScript 在到达这层原型链之前也已经停止了搜索。 # --instructions-- -Override the `fly()` method for `Penguin` so that it returns "Alas, this is a flightless bird." +重写 `Penguin` 的 `fly()` 方法,使其返回字符串 `Alas, this is a flightless bird.` # --hints-- -`penguin.fly()` should return the string "Alas, this is a flightless bird." +`penguin.fly()` 方法应该返回字符串 `Alas, this is a flightless bird.` ```js assert(penguin.fly() === 'Alas, this is a flightless bird.'); ``` -The `bird.fly()` method should return "I am flying!" +The `bird.fly()`方法应该返回字符串 `I am flying!` ```js assert(new Bird().fly() === 'I am flying!'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/remember-to-set-the-constructor-property-when-changing-the-prototype.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/remember-to-set-the-constructor-property-when-changing-the-prototype.md index 76874fedec..dc7c7b7ca6 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/remember-to-set-the-constructor-property-when-changing-the-prototype.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/remember-to-set-the-constructor-property-when-changing-the-prototype.md @@ -1,6 +1,6 @@ --- id: 587d7daf367417b2b2512b80 -title: Remember to Set the Constructor Property when Changing the Prototype +title: 更改原型时,记得设置构造函数属性 challengeType: 1 forumTopicId: 301323 dashedName: remember-to-set-the-constructor-property-when-changing-the-prototype @@ -8,19 +8,21 @@ dashedName: remember-to-set-the-constructor-property-when-changing-the-prototype # --description-- -There is one crucial side effect of manually setting the prototype to a new object. It erases the `constructor` property! This property can be used to check which constructor function created the instance, but since the property has been overwritten, it now gives false results: +手动设置一个新对象的原型有一个重要的副作用。 它清除了 `constructor` 属性! 此属性可以用来检查是哪个构造函数创建了实例,但由于该属性已被覆盖,它现在给出了错误的结果: ```js -duck.constructor === Bird; // false -- Oops -duck.constructor === Object; // true, all objects inherit from Object.prototype -duck instanceof Bird; // true, still works +duck.constructor === Bird; +duck.constructor === Object; +duck instanceof Bird; ``` -To fix this, whenever a prototype is manually set to a new object, remember to define the `constructor` property: +按顺序,这些表达式会返回 `false`、`true` 和 `true`。 + +为了解决这个问题,凡是手动给新对象重新设置过原型对象的,都别忘记在原型对象中定义一个 `constructor` 属性: ```js Bird.prototype = { - constructor: Bird, // define the constructor property + constructor: Bird, numLegs: 2, eat: function() { console.log("nom nom nom"); @@ -33,11 +35,11 @@ Bird.prototype = { # --instructions-- -Define the `constructor` property on the `Dog` `prototype`. +给 `Dog` 的 `prototype` 对象定义一个 `constructor` 属性。 # --hints-- -`Dog.prototype` should set the `constructor` property. +`Dog.prototype` 应该定义一个 `constructor` 属性。 ```js assert(Dog.prototype.constructor === Dog); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/reset-an-inherited-constructor-property.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/reset-an-inherited-constructor-property.md index ce051f75a2..4b868aae92 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/reset-an-inherited-constructor-property.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/reset-an-inherited-constructor-property.md @@ -1,6 +1,6 @@ --- id: 587d7db1367417b2b2512b86 -title: Reset an Inherited Constructor Property +title: 重置一个继承的构造函数属性 challengeType: 1 forumTopicId: 301324 dashedName: reset-an-inherited-constructor-property @@ -8,49 +8,49 @@ dashedName: reset-an-inherited-constructor-property # --description-- -When an object inherits its `prototype` from another object, it also inherits the supertype's constructor property. +当一个对象从另一个对象那里继承了其 `prototype` 时,那它也继承了父类的 constructor 属性。 -Here's an example: +请看下面的举例: ```js function Bird() { } Bird.prototype = Object.create(Animal.prototype); let duck = new Bird(); -duck.constructor // function Animal(){...} +duck.constructor ``` -But `duck` and all instances of `Bird` should show that they were constructed by `Bird` and not `Animal`. To do so, you can manually set `Bird's` constructor property to the `Bird` object: +但是 `duck` 和其他所有 `Bird` 的实例都应该表明它们是由 `Bird` 创建的,而不是由 `Animal` 创建的。 为此,你可以手动把 `Bird's` 的 constructor 属性设置为 `Bird` 对象: ```js Bird.prototype.constructor = Bird; -duck.constructor // function Bird(){...} +duck.constructor ``` # --instructions-- -Fix the code so `duck.constructor` and `beagle.constructor` return their respective constructors. +修改你的代码,使得 `duck.constructor` 和 `beagle.constructor` 返回各自的构造函数。 # --hints-- -`Bird.prototype` should be an instance of `Animal`. +`Bird.prototype` 应该是 `Animal` 的一个实例。 ```js assert(Animal.prototype.isPrototypeOf(Bird.prototype)); ``` -`duck.constructor` should return `Bird`. +`duck.constructor` 应该返回 `Bird`。 ```js assert(duck.constructor === Bird); ``` -`Dog.prototype` should be an instance of `Animal`. +`Dog.prototype` 应该是 `Animal` 的一个实例。 ```js assert(Animal.prototype.isPrototypeOf(Dog.prototype)); ``` -`beagle.constructor` should return `Dog`. +`beagle.constructor` 应该返回 `Dog`。 ```js assert(beagle.constructor === Dog); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/set-the-childs-prototype-to-an-instance-of-the-parent.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/set-the-childs-prototype-to-an-instance-of-the-parent.md index 6e450e1bfe..5984e54ba9 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/set-the-childs-prototype-to-an-instance-of-the-parent.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/set-the-childs-prototype-to-an-instance-of-the-parent.md @@ -1,6 +1,6 @@ --- id: 587d7db1367417b2b2512b85 -title: Set the Child's Prototype to an Instance of the Parent +title: 将子辈的原型设置为父辈的实例 challengeType: 1 forumTopicId: 301325 dashedName: set-the-childs-prototype-to-an-instance-of-the-parent @@ -8,30 +8,30 @@ dashedName: set-the-childs-prototype-to-an-instance-of-the-parent # --description-- -In the previous challenge you saw the first step for inheriting behavior from the supertype (or parent) `Animal`: making a new instance of `Animal`. +在上一个挑战中,我们学习了从超类(或者叫父类) `Animal` 继承其行为的第一个步骤:创建一个 `Animal` 的新实例。 -This challenge covers the next step: set the `prototype` of the subtype (or child)—in this case, `Bird`—to be an instance of `Animal`. +这一节挑战我们将学习第二个步骤:给子类型(或者子类)设置 `prototype`。 这样一来,`Bird` 就是 `Animal` 的一个实例了。 ```js Bird.prototype = Object.create(Animal.prototype); ``` -Remember that the `prototype` is like the "recipe" for creating an object. In a way, the recipe for `Bird` now includes all the key "ingredients" from `Animal`. +请记住,`prototype` 类似于创建对象的“配方”。 从某种意义上来说,`Bird` 对象的配方包含了 `Animal` 的所有关键“成分”。 ```js let duck = new Bird("Donald"); -duck.eat(); // prints "nom nom nom" +duck.eat(); ``` -`duck` inherits all of `Animal`'s properties, including the `eat` method. +`duck` 继承了`Animal` 的所有属性,其中包括了 `eat` 方法。 # --instructions-- -Modify the code so that instances of `Dog` inherit from `Animal`. +修改你的代码,实现一个继承自 `Animal` 的 `Dog` 实例。 # --hints-- -`Dog.prototype` should be an instance of `Animal`. +`Dog.prototype` 应该是 `Animal` 的一个实例。 ```js assert(Animal.prototype.isPrototypeOf(Dog.prototype)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-own-properties.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-own-properties.md index f4f369581c..f0e1b40fe8 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-own-properties.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-own-properties.md @@ -1,6 +1,6 @@ --- id: 587d7dae367417b2b2512b7b -title: Understand Own Properties +title: 了解自有属性 challengeType: 1 forumTopicId: 301326 dashedName: understand-own-properties @@ -8,7 +8,7 @@ dashedName: understand-own-properties # --description-- -In the following example, the `Bird` constructor defines two properties: `name` and `numLegs`: +请看下面的实例,`Bird` 构造函数定义了两个属性:`name` 和 `numLegs`: ```js function Bird(name) { @@ -20,7 +20,7 @@ let duck = new Bird("Donald"); let canary = new Bird("Tweety"); ``` -`name` and `numLegs` are called `own` properties, because they are defined directly on the instance object. That means that `duck` and `canary` each has its own separate copy of these properties. In fact every instance of `Bird` will have its own copy of these properties. The following code adds all of the `own` properties of `duck` to the array `ownProps`: +`name` 和 `numLegs` 被叫做 `own` 属性,因为他们是直接在实例对象上定义的。 这就意味着 `duck` 和 `canary` 这两个对象分别拥有这些属性的独立副本。 事实上,`Bird` 的所有实例都将拥有这些属性的独立副本。 以下的代码将 `duck` 里面所有的 `own` 属性都存到一个叫 `ownProps` 的数组里面: ```js let ownProps = []; @@ -31,28 +31,30 @@ for (let property in duck) { } } -console.log(ownProps); // prints [ "name", "numLegs" ] +console.log(ownProps); ``` +控制台将显示值 `["name", "numLegs"]`。 + # --instructions-- -Add the `own` properties of `canary` to the array `ownProps`. +将 `canary` 对象里面的 `own` 属性添加到 `ownProps` 数组里面。 # --hints-- -`ownProps` should include the values `"numLegs"` and `"name"`. +`ownProps` 应该包含 `numLegs` 和 `name` 两个属性的值。 ```js assert(ownProps.indexOf('name') !== -1 && ownProps.indexOf('numLegs') !== -1); ``` -You should solve this challenge without using the built in method `Object.keys()`. +在不使用内置方法 `Object.keys()` 的前提下完成这个挑战。 ```js assert(!/Object(\.keys|\[(['"`])keys\2\])/.test(code)); ``` -You should solve this challenge without hardcoding the `ownProps` array. +你应该解决这个挑战,而不是硬编码 `ownProps` 数组。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-constructor-property.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-constructor-property.md index 6d1fd731db..da372bdd14 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-constructor-property.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-constructor-property.md @@ -1,6 +1,6 @@ --- id: 587d7daf367417b2b2512b7e -title: Understand the Constructor Property +title: 了解构造函数属性 challengeType: 1 forumTopicId: 301327 dashedName: understand-the-constructor-property @@ -8,17 +8,19 @@ dashedName: understand-the-constructor-property # --description-- -There is a special `constructor` property located on the object instances `duck` and `beagle` that were created in the previous challenges: +在上一个挑战中创建的实例对象 `duck` 和 `beagle` 都有一个特殊的 `constructor` 属性: ```js let duck = new Bird(); let beagle = new Dog(); -console.log(duck.constructor === Bird); //prints true -console.log(beagle.constructor === Dog); //prints true +console.log(duck.constructor === Bird); +console.log(beagle.constructor === Dog); ``` -Note that the `constructor` property is a reference to the constructor function that created the instance. The advantage of the `constructor` property is that it's possible to check for this property to find out what kind of object it is. Here's an example of how this could be used: +这两次 `console.log` 调用都将在控制台中显示 `true`。 + +需要注意到的是这个 `constructor` 属性是对创建这个实例的构造函数的一个引用。 `constructor` 属性的一个好处是可以通过检查这个属性来找出它是一个什么对象。 下面是一个例子,来看看是怎么使用的: ```js function joinBirdFraternity(candidate) { @@ -30,28 +32,27 @@ function joinBirdFraternity(candidate) { } ``` -**Note** -Since the `constructor` property can be overwritten (which will be covered in the next two challenges) it’s generally better to use the `instanceof` method to check the type of an object. +**注意:** 由于 `constructor` 属性可以被重写(在下面两节挑战中将会遇到),所以最好使用`instanceof` 方法来检查对象的类型。 # --instructions-- -Write a `joinDogFraternity` function that takes a `candidate` parameter and, using the `constructor` property, return `true` if the candidate is a `Dog`, otherwise return `false`. +写一个 `joinDogFraternity` 函数,传入一个 `candidate` 参数并使用 `constructor` 属性来判断传入的 candidate 是不是 `Dog` 创建的对象实例,如果是,就返回 `true`,否则返回 `false`。 # --hints-- -`joinDogFraternity` should be defined as a function. +`joinDogFraternity` 应该被定义为一个函数。 ```js assert(typeof joinDogFraternity === 'function'); ``` -`joinDogFraternity` should return true if`candidate` is an instance of `Dog`. +如果 `candidate` 是 `Dog` 的一个对象实例,则 `joinDogFraternity` 函数应该返回 `true`。 ```js assert(joinDogFraternity(new Dog('')) === true); ``` -`joinDogFraternity` should use the `constructor` property. +`joinDogFraternity` 中应该用到 `constructor` 属性。 ```js assert(/\.constructor/.test(code) && !/instanceof/.test(code)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-immediately-invoked-function-expression-iife.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-immediately-invoked-function-expression-iife.md index cc33fc1883..d0b9a8b55f 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-immediately-invoked-function-expression-iife.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-immediately-invoked-function-expression-iife.md @@ -1,6 +1,6 @@ --- id: 587d7db2367417b2b2512b8b -title: Understand the Immediately Invoked Function Expression (IIFE) +title: 了解立即调用函数表达(IIFE) challengeType: 1 forumTopicId: 301328 dashedName: understand-the-immediately-invoked-function-expression-iife @@ -8,30 +8,31 @@ dashedName: understand-the-immediately-invoked-function-expression-iife # --description-- -A common pattern in JavaScript is to execute a function as soon as it is declared: +JavaScript 中的一个常见模式就是,函数在声明后立刻执行: ```js (function () { console.log("Chirp, chirp!"); -})(); // this is an anonymous function expression that executes right away -// Outputs "Chirp, chirp!" immediately +})(); ``` -Note that the function has no name and is not stored in a variable. The two parentheses () at the end of the function expression cause it to be immediately executed or invoked. This pattern is known as an immediately invoked function expression or IIFE. +这是一个匿名函数表达式,立即执行并输出 `Chirp, chirp!`。 + +请注意,函数没有名称,也不存储在变量中。 函数表达式末尾的两个括号()会让它被立即执行或调用。 这种模式被叫做立即调用函数表达式(immediately invoked function expression) 或者IIFE。 # --instructions-- -Rewrite the function `makeNest` and remove its call so instead it's an anonymous immediately invoked function expression (IIFE). +重写函数 `makeNest`,并删除它的调用,取而代之是一个匿名的立即调用函数表达式(IIFE)。 # --hints-- -The function should be anonymous. +该函数应该是匿名的。 ```js assert(/\((function|\(\))(=>|\(\)){?/.test(code.replace(/\s/g, ''))); ``` -Your function should have parentheses at the end of the expression to call it immediately. +函数应该在表达式的末尾有括号,以便立即调用它。 ```js assert(/\(.*(\)\(|\}\(\))\)/.test(code.replace(/[\s;]/g, ''))); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-prototype-chain.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-prototype-chain.md index 7632ddb4b3..01a95e01ac 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-prototype-chain.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-prototype-chain.md @@ -1,6 +1,6 @@ --- id: 587d7db0367417b2b2512b82 -title: Understand the Prototype Chain +title: 了解原型链 challengeType: 1 forumTopicId: 301329 dashedName: understand-the-prototype-chain @@ -8,38 +8,38 @@ dashedName: understand-the-prototype-chain # --description-- -All objects in JavaScript (with a few exceptions) have a `prototype`. Also, an object’s `prototype` itself is an object. +JavaScript 中所有的对象(除了少数例外)都有自己的 `prototype`。 而且,对象的 `prototype` 本身也是一个对象。 ```js function Bird(name) { this.name = name; } -typeof Bird.prototype; // yields 'object' +typeof Bird.prototype; ``` -Because a `prototype` is an object, a `prototype` can have its own `prototype`! In this case, the `prototype` of `Bird.prototype` is `Object.prototype`: +正因为 `prototype` 是一个对象,所以 `prototype` 对象也有它自己的 `prototype`! 这样看来的话,`Bird.prototype` 的 `prototype` 就是 `Object.prototype`: ```js -Object.prototype.isPrototypeOf(Bird.prototype); // returns true +Object.prototype.isPrototypeOf(Bird.prototype); ``` -How is this useful? You may recall the `hasOwnProperty` method from a previous challenge: +这有什么作用呢? 你可能还记得我们在上一个挑战中学到的 `hasOwnProperty` 方法: ```js let duck = new Bird("Donald"); -duck.hasOwnProperty("name"); // yields true +duck.hasOwnProperty("name"); ``` -The `hasOwnProperty` method is defined in `Object.prototype`, which can be accessed by `Bird.prototype`, which can then be accessed by `duck`. This is an example of the `prototype` chain. In this `prototype` chain, `Bird` is the `supertype` for `duck`, while `duck` is the `subtype`. `Object` is a `supertype` for both `Bird` and `duck`. `Object` is a `supertype` for all objects in JavaScript. Therefore, any object can use the `hasOwnProperty` method. +`hasOwnProperty` 是定义在 `Object.prototype` 上的一个方法,尽管在 `Bird.prototype` 和 `duck`上并没有定义该方法,但是我们依然可以在这两个对象上访问到。 这就是 `prototype` 链的一个例子。 在这个`prototype` 链中,`Bird` 是 `duck` 的 `supertype`,而 `duck` 是 `subtype`。 `Object` 则是 `Bird` 和 `duck` 实例共同的 `supertype`。 `Object` 是 JavaScript 中所有对象的 `supertype`,也就是原型链的最顶层。 因此,所有对象都可以访问 `hasOwnProperty` 方法。 # --instructions-- -Modify the code to show the correct prototype chain. +修改以下代码使其展示出正确的原型链。 # --hints-- -Your code should show that `Object.prototype` is the prototype of `Dog.prototype` +你的代码应该展示 `Object.prototype` 是 `Dog.prototype` 的原型。 ```js assert(/Object\.prototype\.isPrototypeOf/.test(code)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-where-an-objects-prototype-comes-from.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-where-an-objects-prototype-comes-from.md index 5644bfa873..6b255e9a6b 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-where-an-objects-prototype-comes-from.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-where-an-objects-prototype-comes-from.md @@ -1,6 +1,6 @@ --- id: 587d7db0367417b2b2512b81 -title: Understand Where an Object’s Prototype Comes From +title: 了解对象的原型来自哪里 challengeType: 1 forumTopicId: 301330 dashedName: understand-where-an-objects-prototype-comes-from @@ -8,7 +8,7 @@ dashedName: understand-where-an-objects-prototype-comes-from # --description-- -Just like people inherit genes from their parents, an object inherits its `prototype` directly from the constructor function that created it. For example, here the `Bird` constructor creates the `duck` object: +就像人们从父母那里继承基因一样,对象也可直接从创建它的构造函数那里继承其 `prototype`。 请看下面的例子:`Bird` 构造函数创建了一个 `duck` 对象: ```js function Bird(name) { @@ -18,20 +18,21 @@ function Bird(name) { let duck = new Bird("Donald"); ``` -`duck` inherits its `prototype` from the `Bird` constructor function. You can show this relationship with the `isPrototypeOf` method: +`duck` 从 `Bird` 构造函数那里继承了它的 `prototype`。 你可以使用 `isPrototypeOf` 方法来验证他们之间的关系: ```js Bird.prototype.isPrototypeOf(duck); -// returns true ``` +这将返回 `true`。 + # --instructions-- -Use `isPrototypeOf` to check the `prototype` of `beagle`. +使用 `isPrototypeOf` 方法验证 `beagle` 的 `prototype`。 # --hints-- -You should show that `Dog.prototype` is the `prototype` of `beagle` +`Dog.prototype` 应该是 `beagle` 的 `prototype`。 ```js assert(/Dog\.prototype\.isPrototypeOf\(beagle\)/.test(code)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-a-constructor-to-create-objects.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-a-constructor-to-create-objects.md index d26baffb1a..4991334b9f 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-a-constructor-to-create-objects.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-a-constructor-to-create-objects.md @@ -1,6 +1,6 @@ --- id: 587d7dad367417b2b2512b78 -title: Use a Constructor to Create Objects +title: 使用构造函数创建对象 challengeType: 1 forumTopicId: 18233 dashedName: use-a-constructor-to-create-objects @@ -8,47 +8,48 @@ dashedName: use-a-constructor-to-create-objects # --description-- -Here's the `Bird` constructor from the previous challenge: +在上一个挑战中,我们用所学到的知识创建了一个 `Bird` 构造函数: ```js function Bird() { this.name = "Albert"; this.color = "blue"; this.numLegs = 2; - // "this" inside the constructor always refers to the object being created } let blueBird = new Bird(); ``` -Notice that the `new` operator is used when calling a constructor. This tells JavaScript to create a new instance of `Bird` called `blueBird`. Without the `new` operator, `this` inside the constructor would not point to the newly created object, giving unexpected results. Now `blueBird` has all the properties defined inside the `Bird` constructor: +**注意:** 构造函数内的 `this` 总是指被创建的对象。 + +注意:通过构造函数创建对象的时候要使用 `new` 操作符。 因为只有这样,JavaScript 才知道要给 `Bird` 这个构造函数创建一个新的实例:`blueBird`。 如果不使用 `new` 操作符来新建对象,那么构造函数里面的 `this` 就无法指向新创建的这个对象实例,从而产生不可预见的错误。 现在 `blueBird` 这个实例就继承了`Bird` 构造函数的所有属性,如下: ```js -blueBird.name; // => Albert -blueBird.color; // => blue -blueBird.numLegs; // => 2 +blueBird.name; +blueBird.color; +blueBird.numLegs; ``` -Just like any other object, its properties can be accessed and modified: +由构造函数创建的实例也和其他对象一样,它的属性可以被访问和修改: ```js blueBird.name = 'Elvira'; -blueBird.name; // => Elvira +blueBird.name; ``` # --instructions-- -Use the `Dog` constructor from the last lesson to create a new instance of `Dog`, assigning it to a variable `hound`. +使用上一个挑战中的 `Dog` 构造函数创建一个 `Dog` 的新实例,并把它赋值给变量 `hound`。 # --hints-- -`hound` should be created using the `Dog` constructor. +`hound` 应该是通过 `Dog` 构造函数来创建的。 ```js assert(hound instanceof Dog); ``` -Your code should use the `new` operator to create an instance of `Dog`. +你的代码中应该使用 `new` 操作符来创建 `Dog` 构造函数的新实例。 ```js assert(code.match(/new/g)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-a-mixin-to-add-common-behavior-between-unrelated-objects.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-a-mixin-to-add-common-behavior-between-unrelated-objects.md index 5664c1e414..62700a63fd 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-a-mixin-to-add-common-behavior-between-unrelated-objects.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-a-mixin-to-add-common-behavior-between-unrelated-objects.md @@ -1,6 +1,6 @@ --- id: 587d7db2367417b2b2512b89 -title: Use a Mixin to Add Common Behavior Between Unrelated Objects +title: 使用 Mixin 在不相关对象之间添加共同行为 challengeType: 1 forumTopicId: 301331 dashedName: use-a-mixin-to-add-common-behavior-between-unrelated-objects @@ -8,9 +8,9 @@ dashedName: use-a-mixin-to-add-common-behavior-between-unrelated-objects # --description-- -As you have seen, behavior is shared through inheritance. However, there are cases when inheritance is not the best solution. Inheritance does not work well for unrelated objects like `Bird` and `Airplane`. They can both fly, but a `Bird` is not a type of `Airplane` and vice versa. +正如你所见,行为是可以通过继承来共享的。 然而,在有些情况下,继承不是最好的解决方案。 继承不适用于不相关的对象,比如 `Bird` 和 `Airplane`。 虽然它们都可以飞行,但是 `Bird` 并不是一种 `Airplane`,反之亦然。 -For unrelated objects, it's better to use mixins. A mixin allows other objects to use a collection of functions. +对于不相关的对象,更好的方法是使用 mixins。 mixin 允许其他对象使用函数集合。 ```js let flyMixin = function(obj) { @@ -20,7 +20,7 @@ let flyMixin = function(obj) { }; ``` -The `flyMixin` takes any object and gives it the `fly` method. +`flyMixin` 能接受任何对象,并为其提供 `fly` 方法。 ```js let bird = { @@ -37,34 +37,36 @@ flyMixin(bird); flyMixin(plane); ``` -Here `bird` and `plane` are passed into `flyMixin`, which then assigns the `fly` function to each object. Now `bird` and `plane` can both fly: +这里的 `flyMixin` 接收了`bird` 和 `plane` 对象,然后将 `fly` 方法分配给了每一个对象。 现在 `bird` 和 `plane` 都可以飞行了: ```js -bird.fly(); // prints "Flying, wooosh!" -plane.fly(); // prints "Flying, wooosh!" +bird.fly(); +plane.fly(); ``` -Note how the mixin allows for the same `fly` method to be reused by unrelated objects `bird` and `plane`. +控制台将显示字符串 `Flying, wooosh!` 两次,每 `.fly()` 调用都会显示。 + +注意观察 mixin 是如何允许相同的 `fly` 方法被不相关的对象 `bird` 和 `plane` 重用的。 # --instructions-- -Create a mixin named `glideMixin` that defines a method named `glide`. Then use the `glideMixin` to give both `bird` and `boat` the ability to glide. +创建一个名为 `glideMixin` 的 mixin,并定义一个 `glide` 方法。 然后使用 `glideMixin` 来给 `bird` 和 `boat` 赋予滑行(glide)的能力。 # --hints-- -Your code should declare a `glideMixin` variable that is a function. +你应该声明一个变量名为 `glideMixin` 的函数。 ```js assert(typeof glideMixin === 'function'); ``` -Your code should use the `glideMixin` on the `bird` object to give it the `glide` method. +你应该在 `bird`上使用 `glideMixin`,以提供 `glide` 方法。 ```js assert(typeof bird.glide === 'function'); ``` -Your code should use the `glideMixin` on the `boat` object to give it the `glide` method. +你应该在 `boat` 上使用 `glideMixin`,以为其提供 `glide` 方法。 ```js assert(typeof boat.glide === 'function'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-an-iife-to-create-a-module.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-an-iife-to-create-a-module.md index 6f5a69f157..7f2c9548a3 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-an-iife-to-create-a-module.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-an-iife-to-create-a-module.md @@ -1,6 +1,6 @@ --- id: 587d7db2367417b2b2512b8c -title: Use an IIFE to Create a Module +title: 使用 IIFE 创建一个模块 challengeType: 1 forumTopicId: 301332 dashedName: use-an-iife-to-create-a-module @@ -8,7 +8,7 @@ dashedName: use-an-iife-to-create-a-module # --description-- -An immediately invoked function expression (IIFE) is often used to group related functionality into a single object or module. For example, an earlier challenge defined two mixins: +一个立即调用函数表达式(IIFE)通常用于将相关功能分组到单个对象或者是 module 中。 例如,先前的挑战中定义了两个 mixins: ```js function glideMixin(obj) { @@ -23,7 +23,7 @@ function flyMixin(obj) { } ``` -We can group these mixins into a module as follows: +我们可以将这些 mixins 分成以下模块: ```js let motionModule = (function () { @@ -39,10 +39,10 @@ let motionModule = (function () { }; } } -})(); // The two parentheses cause the function to be immediately invoked +})(); ``` -Note that you have an immediately invoked function expression (IIFE) that returns an object `motionModule`. This returned object contains all of the mixin behaviors as properties of the object. The advantage of the module pattern is that all of the motion behaviors can be packaged into a single object that can then be used by other parts of your code. Here is an example using it: +注意:一个立即调用函数表达式(IIFE)返回了一个 `motionModule` 对象。 返回的这个对象包含了作为对象属性的所有 mixin 行为。 module 模式的优点是,所有的运动相关的行为都可以打包成一个对象,然后由代码的其他部分使用。 下面是一个使用它的例子: ```js motionModule.glideMixin(duck); @@ -51,23 +51,23 @@ duck.glide(); # --instructions-- -Create a module named `funModule` to wrap the two mixins `isCuteMixin` and `singMixin`. `funModule` should return an object. +创建一个名为 `funModule` 的模块,将这两个 mixins:`isCuteMixin` 和 `singMixin` 包装起来。 `funModule` 应该返回一个对象。 # --hints-- -`funModule` should be defined and return an object. +`funModule` 应该被定义并返回一个对象。 ```js assert(typeof funModule === 'object'); ``` -`funModule.isCuteMixin` should access a function. +`funModule.isCuteMixin` 应该访问一个函数。 ```js assert(typeof funModule.isCuteMixin === 'function'); ``` -`funModule.singMixin` should access a function. +`funModule.singMixin` 应该访问一个函数。 ```js assert(typeof funModule.singMixin === 'function'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-closure-to-protect-properties-within-an-object-from-being-modified-externally.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-closure-to-protect-properties-within-an-object-from-being-modified-externally.md index cdbb9b51c4..c3f1ea65ec 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-closure-to-protect-properties-within-an-object-from-being-modified-externally.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-closure-to-protect-properties-within-an-object-from-being-modified-externally.md @@ -1,7 +1,7 @@ --- id: 587d7db2367417b2b2512b8a title: >- - Use Closure to Protect Properties Within an Object from Being Modified Externally + 使用闭包保护对象内的属性不被外部修改 challengeType: 1 forumTopicId: 18234 dashedName: >- @@ -10,50 +10,49 @@ dashedName: >- # --description-- -In the previous challenge, `bird` had a public property `name`. It is considered public because it can be accessed and changed outside of `bird`'s definition. +在上一次挑战中,`bird` 有一个公共属性 `name`。 公共属性的定义就是:它可以在 `bird` 的定义范围之外被访问和更改。 ```js bird.name = "Duffy"; ``` -Therefore, any part of your code can easily change the name of `bird` to any value. Think about things like passwords and bank accounts being easily changeable by any part of your codebase. That could cause a lot of issues. +因此,代码的任何地方都可以轻松地将 `bird` 的 name 属性更改为任意值。 想想密码和银行账户之类的东西,如果代码库的任何部分都可以轻易改变他们。 那么将会引起很多问题。 -The simplest way to make this public property private is by creating a variable within the constructor function. This changes the scope of that variable to be within the constructor function versus available globally. This way, the variable can only be accessed and changed by methods also within the constructor function. +使属性私有化最简单的方法就是在构造函数中创建变量。 可以将该变量范围限定在构造函数中,而不是全局可用。 这样,属性只能由构造函数中的方法访问和更改。 ```js function Bird() { - let hatchedEgg = 10; // private variable + let hatchedEgg = 10; - /* publicly available method that a bird object can use */ this.getHatchedEggCount = function() { return hatchedEgg; }; } let ducky = new Bird(); -ducky.getHatchedEggCount(); // returns 10 +ducky.getHatchedEggCount(); ``` -Here `getHatchedEggCount` is a privileged method, because it has access to the private variable `hatchedEgg`. This is possible because `hatchedEgg` is declared in the same context as `getHatchedEggCount`. In JavaScript, a function always has access to the context in which it was created. This is called `closure`. +这里的 `getHatchedEggCount` 是一种特权方法,因为它可以访问私有属性 `hatchedEgg`。 这是因为 `hatchedEgg` 是在与 `getHatchedEggCount` 相同的上下文中声明的。 在 JavaScript 中,函数总是可以访问创建它的上下文。 这就叫做 `closure`。 # --instructions-- -Change how `weight` is declared in the `Bird` function so it is a private variable. Then, create a method `getWeight` that returns the value of `weight` 15. +更改在 `Bird` 函数中声明的 `weight` 方法,使其成为私有变量。 然后,创建一个返回 `weight` 值 15 的 `getWeight` 方法。 # --hints-- -The `weight` property should be a private variable and should be assigned the value of `15`. +`weight` 属性应该是一个私有变量,值应该是 `15`。 ```js assert(code.match(/(var|let|const)\s+weight\s*\=\s*15\;?/g)); ``` -Your code should create a method in `Bird` called `getWeight` that returns the value of the private variable `weight`. +你的代码应该在 `Bird` 中创建一个名为 `getWeight` 方法,该方法返回私有变量 `weight`。 ```js assert(new Bird().getWeight() === 15); ``` -Your `getWeight` function should return the private variable `weight`. +你的 `getWeight` 函数应该返回私有变量 `weight`。 ```js assert(code.match(/((return\s+)|(\(\s*\)\s*\=\>\s*))weight\;?/g)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-dot-notation-to-access-the-properties-of-an-object.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-dot-notation-to-access-the-properties-of-an-object.md index b4e34f42f9..55323f076a 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-dot-notation-to-access-the-properties-of-an-object.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-dot-notation-to-access-the-properties-of-an-object.md @@ -1,6 +1,6 @@ --- id: 587d7dac367417b2b2512b74 -title: Use Dot Notation to Access the Properties of an Object +title: 使用点符号来访问对象的属性 challengeType: 1 forumTopicId: 301333 dashedName: use-dot-notation-to-access-the-properties-of-an-object @@ -8,7 +8,7 @@ dashedName: use-dot-notation-to-access-the-properties-of-an-object # --description-- -The last challenge created an object with various properties. Now you'll see how to access the values of those properties. Here's an example: +最后一个挑战创建了一个具有各种属性的对象。 现在你会看到如何访问这些属性的值。 下面是一个示例: ```js let duck = { @@ -16,24 +16,23 @@ let duck = { numLegs: 2 }; console.log(duck.name); -// This prints "Aflac" to the console ``` -Dot notation is used on the object name, `duck`, followed by the name of the property, `name`, to access the value of "Aflac". +我们可以用“点号表示法”来访问对象的属性,`duck` 后面加上点号以及属性名 `name`,来访问到 `Aflac`。 # --instructions-- -Print both properties of the `dog` object to your console. +请在控制台里面输出 `dog` 对象中两个属性的值。 # --hints-- -Your code should use `console.log` to print the value for the `name` property of the `dog` object. +你应该使用 `console.log` 来将 `dog` 对象的 `name` 属性值输出到控制台。 ```js assert(/console.log\(.*dog\.name.*\)/g.test(code)); ``` -Your code should use `console.log` to print the value for the `numLegs` property of the `dog` object. +你应该使用 `console.log` 来将 `dog` 对象的 `numLegs` 属性值输出到控制台。 ```js assert(/console.log\(.*dog\.numLegs.*\)/g.test(code)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-inheritance-so-you-dont-repeat-yourself.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-inheritance-so-you-dont-repeat-yourself.md index 4411c1a12e..b854477576 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-inheritance-so-you-dont-repeat-yourself.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-inheritance-so-you-dont-repeat-yourself.md @@ -1,6 +1,6 @@ --- id: 587d7db0367417b2b2512b83 -title: Use Inheritance So You Don't Repeat Yourself +title: 使用继承避免重复 challengeType: 1 forumTopicId: 301334 dashedName: use-inheritance-so-you-dont-repeat-yourself @@ -8,9 +8,9 @@ dashedName: use-inheritance-so-you-dont-repeat-yourself # --description-- -There's a principle in programming called Don't Repeat Yourself (DRY). The reason repeated code is a problem is because any change requires fixing code in multiple places. This usually means more work for programmers and more room for errors. +有一条原则叫做:Don't Repeat Yourself。常以缩写形式 DRY 出现,意思是“不要自己重复”。 编写重复代码会产生的问题是:任何改变都需要去多个地方修复所有重复的代码。 这通常意味着我们需要做更多的工作,会产生更高的出错率。 -Notice in the example below that the `describe` method is shared by `Bird` and `Dog`: +请观察下面的示例,`Bird` 和 `Dog` 共享 `describe` 方法: ```js Bird.prototype = { @@ -28,7 +28,7 @@ Dog.prototype = { }; ``` -The `describe` method is repeated in two places. The code can be edited to follow the DRY principle by creating a `supertype` (or parent) called `Animal`: +我们可以看到 `describe` 方法在两个地方重复定义了。 根据以上所说的 DRY 原则,我们可以通过创建一个 `Animal` `supertype`(或者父类)来重写这段代码: ```js function Animal() { }; @@ -41,7 +41,7 @@ Animal.prototype = { }; ``` -Since `Animal` includes the `describe` method, you can remove it from `Bird` and `Dog`: +`Animal` 构造函数中定义了 `describe` 方法,可将 `Bird` 和 `Dog` 这两个构造函数的方法删除掉: ```js Bird.prototype = { @@ -55,23 +55,23 @@ Dog.prototype = { # --instructions-- -The `eat` method is repeated in both `Cat` and `Bear`. Edit the code in the spirit of DRY by moving the `eat` method to the `Animal` `supertype`. +`Cat` 和 `Bear` 重复定义了 `eat` 方法。 本着 DRY 的原则,通过将 `eat` 方法移动到 `Animal``supertype` 中来重写你的代码。 # --hints-- -`Animal.prototype` should have the `eat` property. +`Animal.prototype` 应该有 `eat` 属性。 ```js assert(Animal.prototype.hasOwnProperty('eat')); ``` -`Bear.prototype` should not have the `eat` property. +`Bear.prototype` 不应该有 `eat` 属性。 ```js assert(!Bear.prototype.hasOwnProperty('eat')); ``` -`Cat.prototype` should not have the `eat` property. +`Cat.prototype` 不应该有 `eat` 属性。 ```js assert(!Cat.prototype.hasOwnProperty('eat')); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-prototype-properties-to-reduce-duplicate-code.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-prototype-properties-to-reduce-duplicate-code.md index 2f0875f8c3..0f33cf39a6 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-prototype-properties-to-reduce-duplicate-code.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-prototype-properties-to-reduce-duplicate-code.md @@ -1,6 +1,6 @@ --- id: 587d7dae367417b2b2512b7c -title: Use Prototype Properties to Reduce Duplicate Code +title: 使用原型属性来减少重复代码 challengeType: 1 forumTopicId: 301336 dashedName: use-prototype-properties-to-reduce-duplicate-code @@ -8,44 +8,44 @@ dashedName: use-prototype-properties-to-reduce-duplicate-code # --description-- -Since `numLegs` will probably have the same value for all instances of `Bird`, you essentially have a duplicated variable `numLegs` inside each `Bird` instance. +所有 `Bird` 实例可能会有相同的 `numLegs` 值,所以在每一个 `Bird` 的实例中本质上都有一个重复的变量 `numLegs`。 -This may not be an issue when there are only two instances, but imagine if there are millions of instances. That would be a lot of duplicated variables. +当只有两个实例时可能并不是什么问题,但想象一下如果有数百万个实例。 这将会产生许许多多重复的变量。 -A better way is to use `Bird’s` `prototype`. Properties in the `prototype` are shared among ALL instances of `Bird`. Here's how to add `numLegs` to the `Bird prototype`: +这里有一个更好的方法可以解决上述问题,那就是使用 `Bird’s` 的 `prototype`。 `prototype` 是一个可以在所有 `Bird` 实例之间共享的对象。 以下是一个在 `Bird prototype` 中添加 `numLegs` 属性的示例: ```js Bird.prototype.numLegs = 2; ``` -Now all instances of `Bird` have the `numLegs` property. +现在所有的 `Bird` 实例都拥有了共同的 `numLegs` 属性值。 ```js -console.log(duck.numLegs); // prints 2 -console.log(canary.numLegs); // prints 2 +console.log(duck.numLegs); +console.log(canary.numLegs); ``` -Since all instances automatically have the properties on the `prototype`, think of a `prototype` as a "recipe" for creating objects. Note that the `prototype` for `duck` and `canary` is part of the `Bird` constructor as `Bird.prototype`. Nearly every object in JavaScript has a `prototype` property which is part of the constructor function that created it. +由于所有的实例都可以继承 `prototype` 上的属性,所以可以把 `prototype` 看作是创建对象的 "配方"。 请注意:`duck` 和 `canary` 的 `prototype` 属于 `Bird` 的构造函数,即 Bird 的原型 `Bird.prototype`。 JavaScript 中几乎所有的对象都有一个 `prototype` 属性,这个属性是属于它所在的构造函数。 # --instructions-- -Add a `numLegs` property to the `prototype` of `Dog` +给 `Dog` 的 `prototype` 添加一个 `numLegs` 属性。 # --hints-- -`beagle` should have a `numLegs` property. +`beagle` 应该有一个 `numLegs` 属性。 ```js assert(beagle.numLegs !== undefined); ``` -`beagle.numLegs` should be a number. +`beagle.numLegs` 应该是一个数字。 ```js assert(typeof beagle.numLegs === 'number'); ``` -`numLegs` should be a `prototype` property not an `own` property. +`numLegs` 应该是一个 `prototype` 属性而不是一个 `own` 属性。 ```js assert(beagle.hasOwnProperty('numLegs') === false); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/verify-an-objects-constructor-with-instanceof.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/verify-an-objects-constructor-with-instanceof.md index 5c4258a1b4..f797684491 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/verify-an-objects-constructor-with-instanceof.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/object-oriented-programming/verify-an-objects-constructor-with-instanceof.md @@ -1,6 +1,6 @@ --- id: 587d7dae367417b2b2512b7a -title: Verify an Object's Constructor with instanceof +title: 使用 instanceof 验证对象的构造函数 challengeType: 1 forumTopicId: 301337 dashedName: verify-an-objects-constructor-with-instanceof @@ -8,7 +8,7 @@ dashedName: verify-an-objects-constructor-with-instanceof # --description-- -Anytime a constructor function creates a new object, that object is said to be an instance of its constructor. JavaScript gives a convenient way to verify this with the `instanceof` operator. `instanceof` allows you to compare an object to a constructor, returning `true` or `false` based on whether or not that object was created with the constructor. Here's an example: +凡是通过构造函数创建出的新对象,这个对象都叫做这个构造函数的 instance。 JavaScript 提供了一种很简便的方法来验证这个事实,那就是通过 `instanceof` 操作符。 `instanceof` 允许你将对象与构造函数之间进行比较,根据对象是否由这个构造函数创建的返回 `true` 或者 `false`。 以下是一个示例: ```js let Bird = function(name, color) { @@ -19,10 +19,12 @@ let Bird = function(name, color) { let crow = new Bird("Alexis", "black"); -crow instanceof Bird; // => true +crow instanceof Bird; ``` -If an object is created without using a constructor, `instanceof` will verify that it is not an instance of that constructor: +`instanceof` 方法会返回 `true`. + +如果一个对象不是使用构造函数创建的,那么 `instanceof` 将会验证这个对象不是构造函数的实例: ```js let canary = { @@ -31,22 +33,24 @@ let canary = { numLegs: 2 }; -canary instanceof Bird; // => false +canary instanceof Bird; ``` +`instanceof` 方法会返回 `false`。 + # --instructions-- -Create a new instance of the `House` constructor, calling it `myHouse` and passing a number of bedrooms. Then, use `instanceof` to verify that it is an instance of `House`. +给 `House` 构造函数创建一个新实例,取名为 `myHouse` 并且传递一个数字给 bedrooms 参数。 然后使用 `instanceof` 操作符验证这个对象是否为 `House` 的实例。 # --hints-- -`myHouse` should have a `numBedrooms` attribute set to a number. +`myHouse` 应该有一个 `numBedrooms` 属性值被赋为一个数字。 ```js assert(typeof myHouse.numBedrooms === 'number'); ``` -You should verify that `myHouse` is an instance of `House` using the `instanceof` operator. +应该使用 `instanceof` 操作符验证 `myHouse` 这个对象是 `House` 构造函数的一个实例。 ```js assert(/myHouse\s*instanceof\s*House/.test(code)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/check-for-all-or-none.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/check-for-all-or-none.md index 2b8ee673e9..821cbcdfb7 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/check-for-all-or-none.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/check-for-all-or-none.md @@ -1,6 +1,6 @@ --- id: 587d7dba367417b2b2512ba8 -title: Check for All or None +title: 检查全部或无 challengeType: 1 forumTopicId: 301338 dashedName: check-for-all-or-none @@ -8,48 +8,50 @@ dashedName: check-for-all-or-none # --description-- -Sometimes the patterns you want to search for may have parts of it that may or may not exist. However, it may be important to check for them nonetheless. +有时,想要搜寻的匹配模式可能有不确定是否存在的部分。 尽管如此,还是想检查它们。 -You can specify the possible existence of an element with a question mark, `?`. This checks for zero or one of the preceding element. You can think of this symbol as saying the previous element is optional. +为此,可以使用问号 `?` 指定可能存在的元素。 这将检查前面的零个或一个元素。 可以将此符号视为前面的元素是可选的。 -For example, there are slight differences in American and British English and you can use the question mark to match both spellings. +例如,美式英语和英式英语略有不同,可以使用问号来匹配两种拼写。 ```js let american = "color"; let british = "colour"; let rainbowRegex= /colou?r/; -rainbowRegex.test(american); // Returns true -rainbowRegex.test(british); // Returns true +rainbowRegex.test(american); +rainbowRegex.test(british); ``` +上面的 `test` 都会返回 `true`。 + # --instructions-- -Change the regex `favRegex` to match both the American English (favorite) and the British English (favourite) version of the word. +修改正则表达式 `favRegex` 以匹配美式英语(`favorite`)和英式英语(`favourite`)的单词版本。 # --hints-- -Your regex should use the optional symbol, `?`. +你的正则表达式应该使用可选符号 `?`。 ```js favRegex.lastIndex = 0; assert(favRegex.source.match(/\?/).length > 0); ``` -Your regex should match `"favorite"` +你的正则表达式应该匹配 `favorite`。 ```js favRegex.lastIndex = 0; assert(favRegex.test('favorite')); ``` -Your regex should match `"favourite"` +你的正则表达式应该匹配 `favourite`。 ```js favRegex.lastIndex = 0; assert(favRegex.test('favourite')); ``` -Your regex should not match `"fav"` +你的正则表达式不应该匹配 `fav`。 ```js favRegex.lastIndex = 0; diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/check-for-mixed-grouping-of-characters.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/check-for-mixed-grouping-of-characters.md index 1b47e0c90e..881dc07423 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/check-for-mixed-grouping-of-characters.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/check-for-mixed-grouping-of-characters.md @@ -1,6 +1,6 @@ --- id: 5c3dda8b4d8df89bea71600f -title: Check For Mixed Grouping of Characters +title: 检查混合字符组 challengeType: 1 forumTopicId: 301339 dashedName: check-for-mixed-grouping-of-characters @@ -8,62 +8,63 @@ dashedName: check-for-mixed-grouping-of-characters # --description-- -Sometimes we want to check for groups of characters using a Regular Expression and to achieve that we use parentheses `()`. +有时候我们想使用正则表达式里的括号 `()` 来检查字符组。 -If you want to find either `Penguin` or `Pumpkin` in a string, you can use the following Regular Expression: `/P(engu|umpk)in/g` +如果想在字符串找到 `Penguin` 或 `Pumpkin`,可以用这个正则表达式:`/P(engu|umpk)in/g`。 -Then check whether the desired string groups are in the test string by using the `test()` method. +然后使用 `test()` 方法检查 test 字符串里面是否包含字符组。 ```js let testStr = "Pumpkin"; let testRegex = /P(engu|umpk)in/; testRegex.test(testStr); -// Returns true ``` +`test` 方法会返回 `true`。 + # --instructions-- -Fix the regex so that it checks for the names of `Franklin Roosevelt` or `Eleanor Roosevelt` in a case sensitive manner and it should make concessions for middle names. +完善正则表达式,使其以区分大小写的方式检查 `Franklin Roosevelt` 或 `Eleanor Roosevelt` 的名字,并且应该忽略 middle names。 -Then fix the code so that the regex that you have created is checked against `myString` and either `true` or `false` is returned depending on whether the regex matches. +然后完善代码,使创建的正则检查 `myString`,根据正则是否匹配返回 `true` 或 `false`。 # --hints-- -Your regex `myRegex` should return `true` for the string `Franklin D. Roosevelt` +正则 `myRegex` 测试 `Franklin D. Roosevelt` 应该返回 `true`。 ```js myRegex.lastIndex = 0; assert(myRegex.test('Franklin D. Roosevelt')); ``` -Your regex `myRegex` should return `true` for the string `Eleanor Roosevelt` +正则 `myRegex` 测试 `Eleanor Roosevelt` 应该返回 `true`。 ```js myRegex.lastIndex = 0; assert(myRegex.test('Eleanor Roosevelt')); ``` -Your regex `myRegex` should return `false` for the string `Franklin Rosevelt` +正则 `myRegex` 测试 `Franklin Rosevelt` 应该返回 `false`。 ```js myRegex.lastIndex = 0; assert(!myRegex.test('Franklin Rosevelt')); ``` -Your regex `myRegex` should return `false` for the string `Frank Roosevelt` +正则 `myRegex` 测试 `Frank Roosevelt` 应该返回 `false`。 ```js myRegex.lastIndex = 0; assert(!myRegex.test('Frank Roosevelt')); ``` -You should use `.test()` to test the regex. +你应该使用 `.test()` 方法来检测正则表达式。 ```js assert(code.match(/myRegex.test\(\s*myString\s*\)/)); ``` -Your result should return `true`. +你的返回结果应该为 `true`。 ```js assert(result === true); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/extract-matches.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/extract-matches.md index 293eb6da97..c74f6153d1 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/extract-matches.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/extract-matches.md @@ -1,6 +1,6 @@ --- id: 587d7db4367417b2b2512b92 -title: Extract Matches +title: 提取匹配项 challengeType: 1 forumTopicId: 301340 dashedName: extract-matches @@ -8,22 +8,22 @@ dashedName: extract-matches # --description-- -So far, you have only been checking if a pattern exists or not within a string. You can also extract the actual matches you found with the `.match()` method. +到目前为止,只是检查了一个匹配模式是否存在于字符串中。 还可以使用 `.match()` 方法来提取找到的实际匹配项。 -To use the `.match()` method, apply the method on a string and pass in the regex inside the parentheses. +可以使用字符串来调用 `.match()` 方法,并在括号内传入正则表达式。 -Here's an example: +请看下面的举例: ```js "Hello, World!".match(/Hello/); -// Returns ["Hello"] let ourStr = "Regular expressions"; let ourRegex = /expressions/; ourStr.match(ourRegex); -// Returns ["expressions"] ``` -Note that the `.match` syntax is the "opposite" of the `.test` method you have been using thus far: +这里第一个 `match` 将返回 `["Hello"]` 第二个将返回 `["expressions"]`。 + +请注意, `.match` 语法是目前为止一直使用的 `.test` 方法中的“反向”: ```js 'string'.match(/regex/); @@ -32,23 +32,23 @@ Note that the `.match` syntax is the "opposite" of the `.test` method you have b # --instructions-- -Apply the `.match()` method to extract the word `coding`. +利用 `.match()` 方法提取单词 `coding`。 # --hints-- -The `result` should have the word `coding` +`result` 应该有字符串 `coding` ```js assert(result.join() === 'coding'); ``` -Your regex `codingRegex` should search for `coding` +您的 regex `codingRegex` 应该搜索字符串 `coding` ```js assert(codingRegex.source === 'coding'); ``` -You should use the `.match()` method. +您应该使用 `.match()` 方法。 ```js assert(code.match(/\.match\(.*\)/)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/find-characters-with-lazy-matching.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/find-characters-with-lazy-matching.md index df05cd9717..5912f00bd1 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/find-characters-with-lazy-matching.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/find-characters-with-lazy-matching.md @@ -1,6 +1,6 @@ --- id: 587d7db6367417b2b2512b9b -title: Find Characters with Lazy Matching +title: 用惰性匹配来查找字符 challengeType: 1 forumTopicId: 301341 dashedName: find-characters-with-lazy-matching @@ -8,36 +8,35 @@ dashedName: find-characters-with-lazy-matching # --description-- -In regular expressions, a greedy match finds the longest possible part of a string that fits the regex pattern and returns it as a match. The alternative is called a lazy match, which finds the smallest possible part of the string that satisfies the regex pattern. +在正则表达式中,贪婪(greedy)匹配会匹配到符合正则表达式匹配模式的字符串的最长可能部分,并将其作为匹配项返回。 另一种方案称为懒惰(lazy)匹配,它会匹配到满足正则表达式的字符串的最小可能部分。 -You can apply the regex `/t[a-z]*i/` to the string `"titanic"`. This regex is basically a pattern that starts with `t`, ends with `i`, and has some letters in between. +可以将正则表达式 `/t[a-z]*i/` 应用于字符串 `"titanic"`。 这个正则表达式是一个以 `t` 开始,以 `i` 结束,并且中间有一些字母的匹配模式。 -Regular expressions are by default greedy, so the match would return `["titani"]`. It finds the largest sub-string possible to fit the pattern. +正则表达式默认是贪婪匹配,因此匹配返回为 `["titani"]`。 它会匹配到适合该匹配模式的最大子字符串。 -However, you can use the `?` character to change it to lazy matching. `"titanic"` matched against the adjusted regex of `/t[a-z]*?i/` returns `["ti"]`. +但是,你可以使用 `?` 字符来将其变成懒惰匹配。 调整后的正则表达式 `/t[a-z]*?i/` 匹配字符串 `"titanic"` 返回 `["ti"]`。 -**Note** -Parsing HTML with regular expressions should be avoided, but pattern matching an HTML string with regular expressions is completely fine. +**注意:**应该避免使用正则表达式解析 HTML,但是可以用正则表达式匹配 HTML 字符串。 # --instructions-- -Fix the regex `/<.*>/` to return the HTML tag `

` and not the text `"

Winter is coming

"`. Remember the wildcard `.` in a regular expression matches any character. +修复正则表达式 `/<.*>/`,让它返回 HTML 标签 `

`,而不是文本 `"

Winter is coming

"`。 请记得在正则表达式中使用通配符 `.` 来匹配任意字符。 # --hints-- -The `result` variable should be an array with `

` in it +`result` 变量应该是一个包含 `

` 的数组 ```js assert(result[0] == '

'); ``` -`myRegex` should use lazy matching +`myRegex` 应该使用懒惰匹配 ```js assert(/\?/g.test(myRegex)); ``` -`myRegex` should not include the string 'h1' +`myRegex` 不应包含字符串 `h1` ```js assert(!myRegex.source.match('h1')); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/find-more-than-the-first-match.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/find-more-than-the-first-match.md index cb76eff45d..a96dac59fb 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/find-more-than-the-first-match.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/find-more-than-the-first-match.md @@ -1,6 +1,6 @@ --- id: 587d7db4367417b2b2512b93 -title: Find More Than the First Match +title: 全局匹配 challengeType: 1 forumTopicId: 301342 dashedName: find-more-than-the-first-match @@ -8,45 +8,47 @@ dashedName: find-more-than-the-first-match # --description-- -So far, you have only been able to extract or search a pattern once. +到目前为止,只能提取或搜寻一次模式匹配。 ```js let testStr = "Repeat, Repeat, Repeat"; let ourRegex = /Repeat/; testStr.match(ourRegex); -// Returns ["Repeat"] ``` -To search or extract a pattern more than once, you can use the `g` flag. +在这里 `match` 将返回 `["Repeat"]`。 + +若要多次搜寻或提取模式匹配,可以使用 `g` 标志。 ```js let repeatRegex = /Repeat/g; testStr.match(repeatRegex); -// Returns ["Repeat", "Repeat", "Repeat"] ``` +这里 `match` 返回值 `["Repeat", "Repeat", "Repeat"]` + # --instructions-- -Using the regex `starRegex`, find and extract both `"Twinkle"` words from the string `twinkleStar`. +使用正则表达式 `starRegex`,从字符串 `twinkleStar` 中匹配所有的 `Twinkle` 单词并提取出来。 -**Note** -You can have multiple flags on your regex like `/search/gi` +**注意:** +在正则表达式上可以有多个标志,比如 `/search/gi` # --hints-- -Your regex `starRegex` should use the global flag `g` +你的正则表达式 `starRegex` 应该使用全局标志 `g` ```js assert(starRegex.flags.match(/g/).length == 1); ``` -Your regex `starRegex` should use the case insensitive flag `i` +你的正则表达式 `starRegex` 应该使用忽略大小写标志 `i` ```js assert(starRegex.flags.match(/i/).length == 1); ``` -Your match should match both occurrences of the word `"Twinkle"` +你的匹配应该匹配单词 `Twinkle` 的两个匹配项 ```js assert( @@ -58,7 +60,7 @@ assert( ); ``` -Your match `result` should have two elements in it. +你的匹配 `result` 应该包含两个元素 ```js assert(result.length == 2); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/find-one-or-more-criminals-in-a-hunt.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/find-one-or-more-criminals-in-a-hunt.md index e94ab1943c..9be3c35015 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/find-one-or-more-criminals-in-a-hunt.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/find-one-or-more-criminals-in-a-hunt.md @@ -1,6 +1,6 @@ --- id: 587d7db7367417b2b2512b9c -title: Find One or More Criminals in a Hunt +title: 在狩猎中找到一个或多个罪犯 challengeType: 1 forumTopicId: 301343 dashedName: find-one-or-more-criminals-in-a-hunt @@ -8,11 +8,11 @@ dashedName: find-one-or-more-criminals-in-a-hunt # --description-- -Time to pause and test your new regex writing skills. A group of criminals escaped from jail and ran away, but you don't know how many. However, you do know that they stay close together when they are around other people. You are responsible for finding all of the criminals at once. +是时候停一停来测试你的正则表达式使用能力了。 一群罪犯越狱逃跑了,但你不知道有多少人。 然而,你知道他们不在一起时会保持紧密联系。 你有责任立刻找到所有的罪犯。 -Here's an example to review how to do this: +这里有一个示例来提示如何做到这一点: -The regex `/z+/` matches the letter `z` when it appears one or more times in a row. It would find matches in all of the following strings: +当字母`z`在一行中出现一次或连续多次时,正则表达式`/z+/`会匹配到它。 它会在以下所有字符串中找到匹配项: ```js "z" @@ -22,7 +22,7 @@ The regex `/z+/` matches the letter `z` when it appears one or more times in a r "abczzzzzzzzzzzzzzzzzzzzzabc" ``` -But it does not find matches in the following strings since there are no letter `z` characters: +但是它不会在以下字符串中找到匹配项,因为它们中没有字母`z`: ```js "" @@ -32,32 +32,32 @@ But it does not find matches in the following strings since there are no letter # --instructions-- -Write a greedy regex that finds one or more criminals within a group of other people. A criminal is represented by the capital letter `C`. +编写一个贪婪正则表达式,在一组其他人中匹配到一个或多个罪犯。 罪犯由大写字母`C`表示。 # --hints-- -Your regex should match one criminal (`C`) in `"C"` +您的正则表达式应该匹配字符串 `C` 中的一个罪犯(`C`) ```js assert('C'.match(reCriminals) && 'C'.match(reCriminals)[0] == 'C'); ``` -Your regex should match two criminals (`CC`) in `"CC"` +您的正则表达式应该匹配字符串 `CC` 中的两个罪犯(`CC`) ```js assert('CC'.match(reCriminals) && 'CC'.match(reCriminals)[0] == 'CC'); ``` -Your regex should match three criminals (`CCC`) in `"P1P5P4CCCP2P6P3"` +您的正则表达式应该在字符串 `P1P5P4CCCcP2P6P3` 中匹配三个罪犯(`CCC`)。 ```js assert( - 'P1P5P4CCCP2P6P3'.match(reCriminals) && - 'P1P5P4CCCP2P6P3'.match(reCriminals)[0] == 'CCC' + 'P1P5P4CCCcP2P6P3'.match(reCriminals) && + 'P1P5P4CCCcP2P6P3'.match(reCriminals)[0] == 'CCC' ); ``` -Your regex should match five criminals (`CCCCC`) in `"P6P2P7P4P5CCCCCP3P1"` +您的正则表达式应该在字符串 `P6P2P7P4P5CCCCCP3P1`中匹配五个罪犯(`CCCCC`) ```js assert( @@ -66,19 +66,19 @@ assert( ); ``` -Your regex should not match any criminals in `""` +你的正则表达式在`""`中不应该匹配到任何罪犯 ```js assert(!reCriminals.test('')); ``` -Your regex should not match any criminals in `"P1P2P3"` +你的正则表达式在`P1P2P3`中不应该匹配到任何罪犯 ```js assert(!reCriminals.test('P1P2P3')); ``` -Your regex should match fifty criminals (`CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC`) in `"P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3"`. +你的正则表达式应该在`P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3`中匹配五十个 罪犯('`CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC`')。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/ignore-case-while-matching.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/ignore-case-while-matching.md index 8ea7f4218e..1ec17884aa 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/ignore-case-while-matching.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/ignore-case-while-matching.md @@ -1,6 +1,6 @@ --- id: 587d7db4367417b2b2512b91 -title: Ignore Case While Matching +title: 匹配时忽略大小写 challengeType: 1 forumTopicId: 301344 dashedName: ignore-case-while-matching @@ -8,73 +8,73 @@ dashedName: ignore-case-while-matching # --description-- -Up until now, you've looked at regexes to do literal matches of strings. But sometimes, you might want to also match case differences. +到目前为止,已经了解了如何用正则表达式来执行字符串的匹配。 但有时候,并不关注匹配字母的大小写。 -Case (or sometimes letter case) is the difference between uppercase letters and lowercase letters. Examples of uppercase are `"A"`, `"B"`, and `"C"`. Examples of lowercase are `"a"`, `"b"`, and `"c"`. +大小写即大写字母和小写字母。 大写字母如 `A`、`B` 和 `C`。 小写字母如 `a`、`b` 和 `c`。 -You can match both cases using what is called a flag. There are other flags but here you'll focus on the flag that ignores case - the `i` flag. You can use it by appending it to the regex. An example of using this flag is `/ignorecase/i`. This regex can match the strings `"ignorecase"`, `"igNoreCase"`, and `"IgnoreCase"`. +可以使用标志(flag)来匹配这两种情况。 标志有很多,不过这里我们只关注忽略大小写的标志——`i`。 可以通过将它附加到正则表达式之后来使用它。 这里给出使用该标志的一个实例 `/ignorecase/i`。 这个字符串可以匹配字符串 `ignorecase`、`igNoreCase` 和 `IgnoreCase`。 # --instructions-- -Write a regex `fccRegex` to match `"freeCodeCamp"`, no matter its case. Your regex should not match any abbreviations or variations with spaces. +编写正则表达式 `fccRegex` 以匹配 `freeCodeCamp`,忽略大小写。 正则表达式不应与任何缩写或带有空格的变体匹配。 # --hints-- -Your regex should match `freeCodeCamp` +你的正则表达式应该匹配 `freeCodeCamp` ```js assert(fccRegex.test('freeCodeCamp')); ``` -Your regex should match `FreeCodeCamp` +你的正则表达式应该匹配 `FreeCodeCamp` ```js assert(fccRegex.test('FreeCodeCamp')); ``` -Your regex should match `FreecodeCamp` +你的正则表达式应该匹配 `FreecodeCamp` ```js assert(fccRegex.test('FreecodeCamp')); ``` -Your regex should match `FreeCodecamp` +你的正则表达式应该匹配 `FreeCodecamp` ```js assert(fccRegex.test('FreeCodecamp')); ``` -Your regex should not match `Free Code Camp` +你的正则表达式不应该匹配 `Free Code Camp` ```js assert(!fccRegex.test('Free Code Camp')); ``` -Your regex should match `FreeCOdeCamp` +您的正则表达式应该匹配字符串 `FreeCOdeCamp` ```js assert(fccRegex.test('FreeCOdeCamp')); ``` -Your regex should not match `FCC` +你的正则表达式不应该匹配 `FCC` ```js assert(!fccRegex.test('FCC')); ``` -Your regex should match `FrEeCoDeCamp` +你的正则表达式应该匹配字符串 `FrEeCoDeCamp` ```js assert(fccRegex.test('FrEeCoDeCamp')); ``` -Your regex should match `FrEeCodECamp` +你的正则表达式应该匹配字符串 `FrEeCodECamp` ```js assert(fccRegex.test('FrEeCodECamp')); ``` -Your regex should match `FReeCodeCAmp` +你的正则表达式应该匹配字符串 `FReeCodeCAmp` ```js assert(fccRegex.test('FReeCodeCAmp')); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-a-literal-string-with-different-possibilities.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-a-literal-string-with-different-possibilities.md index c98f45b851..b253f60c18 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-a-literal-string-with-different-possibilities.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-a-literal-string-with-different-possibilities.md @@ -1,6 +1,6 @@ --- id: 587d7db4367417b2b2512b90 -title: Match a Literal String with Different Possibilities +title: 同时用多种模式匹配文字字符串 challengeType: 1 forumTopicId: 301345 dashedName: match-a-literal-string-with-different-possibilities @@ -8,57 +8,57 @@ dashedName: match-a-literal-string-with-different-possibilities # --description-- -Using regexes like `/coding/`, you can look for the pattern `"coding"` in another string. +使用正则表达式`/coding/`,你可以在其他字符串中查找`coding`。 -This is powerful to search single strings, but it's limited to only one pattern. You can search for multiple patterns using the `alternation` or `OR` operator: `|`. +这对于搜寻单个字符串非常有用,但仅限于一种匹配模式。 你可以使用 `alternation` 或 `OR` 操作符搜索多个模式: `|` -This operator matches patterns either before or after it. For example, if you wanted to match `"yes"` or `"no"`, the regex you want is `/yes|no/`. +此操作符匹配操作符前面或后面的字符。 例如,如果你想匹配 `yes` 或 `no`,你需要的正则表达式是 `/yes|no/`。 -You can also search for more than just two patterns. You can do this by adding more patterns with more `OR` operators separating them, like `/yes|no|maybe/`. +你还可以匹配多个规则,这可以通过添加更多的匹配模式来实现。 这些匹配模式将包含更多的 `OR` 操作符来分隔它们,比如`/yes|no|maybe/`。 # --instructions-- -Complete the regex `petRegex` to match the pets `"dog"`, `"cat"`, `"bird"`, or `"fish"`. +完成正则表达式 `petRegex` 以匹配 `dog`、`cat`、`bird` 或者 `fish`。 # --hints-- -Your regex `petRegex` should return `true` for the string `"John has a pet dog."` +对于字符串 `John has a pet dog.`,你的正则表达式`petRegex` 应该返回 `true` ```js assert(petRegex.test('John has a pet dog.')); ``` -Your regex `petRegex` should return `false` for the string `"Emma has a pet rock."` +对于字符串 `Emma has a pet rock.`,你的正则表达式 `petRegex` 的应该返回 `false` ```js assert(!petRegex.test('Emma has a pet rock.')); ``` -Your regex `petRegex` should return `true` for the string `"Emma has a pet bird."` +对于字符串 `Emma has a pet bird.`,你的正则表达式 `petRegex` 应该返回 `true` ```js assert(petRegex.test('Emma has a pet bird.')); ``` -Your regex `petRegex` should return `true` for the string `"Liz has a pet cat."` +对于字符串 `Liz has a pet cat.`,你的正则表达式 `petRegex` 应该返回 `true` ```js assert(petRegex.test('Liz has a pet cat.')); ``` -Your regex `petRegex` should return `false` for the string `"Kara has a pet dolphin."` +对于字符串 `Kara has a pet dolphin.`,你的正则表达式 `petRegex` 应该返回 `false` ```js assert(!petRegex.test('Kara has a pet dolphin.')); ``` -Your regex `petRegex` should return `true` for the string `"Alice has a pet fish."` +对于字符串 `Alice has a pet fish.`,你的正则表达式 `petRegex` 应该返回 `true`。 ```js assert(petRegex.test('Alice has a pet fish.')); ``` -Your regex `petRegex` should return `false` for the string `"Jimmy has a pet computer."` +对于字符串 `Jimmy has a pet computer.`,你的正则表达式 `petRegex` 应该返回 `false`。 ```js assert(!petRegex.test('Jimmy has a pet computer.')); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-letters-and-numbers.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-letters-and-numbers.md index 70cb70395a..8d6b0d45cf 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-letters-and-numbers.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-letters-and-numbers.md @@ -1,6 +1,6 @@ --- id: 587d7db7367417b2b2512b9f -title: Match All Letters and Numbers +title: 匹配所有的字母和数字 challengeType: 1 forumTopicId: 301346 dashedName: match-all-letters-and-numbers @@ -8,42 +8,44 @@ dashedName: match-all-letters-and-numbers # --description-- -Using character classes, you were able to search for all letters of the alphabet with `[a-z]`. This kind of character class is common enough that there is a shortcut for it, although it includes a few extra characters as well. +使用元字符,可以使用 `[a-z]` 搜寻字母表中的所有字母。 这种元字符是很常见的,它有一个缩写,但这个缩写也包含额外的字符。 -The closest character class in JavaScript to match the alphabet is `\w`. This shortcut is equal to `[A-Za-z0-9_]`. This character class matches upper and lowercase letters plus numbers. Note, this character class also includes the underscore character (`_`). +JavaScript 中与字母表匹配的最接近的元字符是`\w`。 这个缩写等同于`[A-Za-z0-9_]`。 此字符类匹配上面字母和小写字母以及数字。 注意,这个字符类也包含下划线字符 (`_`)。 ```js let longHand = /[A-Za-z0-9_]+/; let shortHand = /\w+/; let numbers = "42"; let varNames = "important_var"; -longHand.test(numbers); // Returns true -shortHand.test(numbers); // Returns true -longHand.test(varNames); // Returns true -shortHand.test(varNames); // Returns true +longHand.test(numbers); +shortHand.test(numbers); +longHand.test(varNames); +shortHand.test(varNames); ``` -These shortcut character classes are also known as shorthand character classes. +上面的 `test` 都会返回 `true`。 + +这些元字符缩写也被称为短语元字符 shorthand character classes。 # --instructions-- -Use the shorthand character class `\w` to count the number of alphanumeric characters in various quotes and strings. +使用元字符 `\w` 来计算所有引号中字母和数字字符的数量。 # --hints-- -Your regex should use the global flag. +您的正则表达式应该使用全局标识。 ```js assert(alphabetRegexV2.global); ``` -Your regex should use the shorthand character `\w` to match all characters which are alphanumeric. +正则表达式应该使用元字符r `\w` 来匹配非字母字符。 ```js assert(/\\w/.test(alphabetRegexV2.source)); ``` -Your regex should find 31 alphanumeric characters in `"The five boxing wizards jump quickly."` +你的正则表达式应该在 `The five boxing wizards jump quickly.` 中匹配到 31 个非字母数字字符。 ```js assert( @@ -51,7 +53,7 @@ assert( ); ``` -Your regex should find 32 alphanumeric characters in `"Pack my box with five dozen liquor jugs."` +你的正则表达式应该在 `Pack my box with five dozen liquor jugs.` 中匹配到 32 个非字母数字字符。 ```js assert( @@ -60,7 +62,7 @@ assert( ); ``` -Your regex should find 30 alphanumeric characters in `"How vexingly quick daft zebras jump!"` +你的正则表达式应该在 `How vexingly quick daft zebras jump!` 中匹配到 30 个非字母数字字符。 ```js assert( @@ -68,7 +70,7 @@ assert( ); ``` -Your regex should find 36 alphanumeric characters in `"123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ."` +你的正则表达式应该在字符串 `123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.` 中找到36个字母数字字符。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-non-numbers.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-non-numbers.md index 2290a226d9..d1b8c9d585 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-non-numbers.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-non-numbers.md @@ -1,6 +1,6 @@ --- id: 587d7db8367417b2b2512ba1 -title: Match All Non-Numbers +title: 匹配所有非数字 challengeType: 1 forumTopicId: 301347 dashedName: match-all-non-numbers @@ -8,59 +8,59 @@ dashedName: match-all-non-numbers # --description-- -The last challenge showed how to search for digits using the shortcut `\d` with a lowercase `d`. You can also search for non-digits using a similar shortcut that uses an uppercase `D` instead. +上一项挑战中展示了如何使用带有小写 `d` 的缩写 `\d` 来搜寻数字。 也可以使用类似的缩写来搜寻非数字,该缩写使用大写的 `D`。 -The shortcut to look for non-digit characters is `\D`. This is equal to the character class `[^0-9]`, which looks for a single character that is not a number between zero and nine. +查找非数字字符的缩写是 `\D`。 这等同于字符串 `[^0-9]`,它查找不是 0 - 9 之间数字的单个字符。 # --instructions-- -Use the shorthand character class for non-digits `\D` to count how many non-digits are in movie titles. +使用非数字缩写 `\D` 来计算电影标题中有多少非数字。 # --hints-- -Your regex should use the shortcut character to match non-digit characters +你的正则表达式应该使用缩写来匹配非数字字符。 ```js assert(/\\D/.test(noNumRegex.source)); ``` -Your regex should use the global flag. +你的正则表达式应该使用全局标识。 ```js assert(noNumRegex.global); ``` -Your regex should find no non-digits in `"9"`. +你的正则表达式在 `9` 中应该匹配不到非数字。 ```js assert('9'.match(noNumRegex) == null); ``` -Your regex should find 6 non-digits in `"Catch 22"`. +你的正则表达式应该在 `Catch 22` 中匹配到 6 个非数字。 ```js assert('Catch 22'.match(noNumRegex).length == 6); ``` -Your regex should find 11 non-digits in `"101 Dalmatians"`. +你的正则表达式应该在 `101 Dalmatians` 中匹配到 11 个非数字。 ```js assert('101 Dalmatians'.match(noNumRegex).length == 11); ``` -Your regex should find 15 non-digits in `"One, Two, Three"`. +你的正则表达式应该在 `One, Two, Three` 中匹配到 15 个非数字。 ```js assert('One, Two, Three'.match(noNumRegex).length == 15); ``` -Your regex should find 12 non-digits in `"21 Jump Street"`. +你的正则表达式应该在 `21 Jump Street` 中匹配到 12 个非数字。 ```js assert('21 Jump Street'.match(noNumRegex).length == 12); ``` -Your regex should find 17 non-digits in `"2001: A Space Odyssey"`. +你的正则表达式应该在 `2001: A Space Odyssey` 中匹配到 17 个非数字。 ```js assert('2001: A Space Odyssey'.match(noNumRegex).length == 17); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-numbers.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-numbers.md index 86c84f015a..24a7f6129b 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-numbers.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-numbers.md @@ -1,6 +1,6 @@ --- id: 5d712346c441eddfaeb5bdef -title: Match All Numbers +title: 匹配所有数字 challengeType: 1 forumTopicId: 18181 dashedName: match-all-numbers @@ -8,59 +8,59 @@ dashedName: match-all-numbers # --description-- -You've learned shortcuts for common string patterns like alphanumerics. Another common pattern is looking for just digits or numbers. +已经了解了常见字符串匹配模式的元字符,如字母数字。 另一个常见的匹配模式是只寻找数字。 -The shortcut to look for digit characters is `\d`, with a lowercase `d`. This is equal to the character class `[0-9]`, which looks for a single character of any number between zero and nine. +查找数字字符的缩写是 `\d`,注意是小写的 `d`。 这等同于元字符 `[0-9]`,它查找 0 到 9 之间任意数字的单个字符。 # --instructions-- -Use the shorthand character class `\d` to count how many digits are in movie titles. Written out numbers ("six" instead of 6) do not count. +使用缩写 `\d` 来计算电影标题中有多少个数字。 书面数字("six" 而不是 6)不计算在内。 # --hints-- -Your regex should use the shortcut character to match digit characters +你的正则表达式应该使用缩写来匹配数字字符。 ```js assert(/\\d/.test(numRegex.source)); ``` -Your regex should use the global flag. +您的正则表达式应该使用全局标识。 ```js assert(numRegex.global); ``` -Your regex should find 1 digit in `"9"`. +你的正则表达式应该在 `9` 中匹配到 1 个数字。 ```js assert('9'.match(numRegex).length == 1); ``` -Your regex should find 2 digits in `"Catch 22"`. +你的正则表达式应该在 `Catch 22` 中匹配到 2 个数字。 ```js assert('Catch 22'.match(numRegex).length == 2); ``` -Your regex should find 3 digits in `"101 Dalmatians"`. +你的正则表达式应该在 `101 Dalmatians` 中匹配到 3 个数字。 ```js assert('101 Dalmatians'.match(numRegex).length == 3); ``` -Your regex should find no digits in `"One, Two, Three"`. +你的正则表达式在 `One, Two, Three` 中应该匹配不到数字。 ```js assert('One, Two, Three'.match(numRegex) == null); ``` -Your regex should find 2 digits in `"21 Jump Street"`. +你的正则表达式应该在 `21 Jump Street` 中匹配到 2 个数字。 ```js assert('21 Jump Street'.match(numRegex).length == 2); ``` -Your regex should find 4 digits in `"2001: A Space Odyssey"`. +你的正则表达式应该在 `2001: A Space Odyssey` 中匹配到 4 个数字。 ```js assert('2001: A Space Odyssey'.match(numRegex).length == 4); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-anything-with-wildcard-period.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-anything-with-wildcard-period.md index 64c17e62a6..1ae4d507da 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-anything-with-wildcard-period.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-anything-with-wildcard-period.md @@ -1,6 +1,6 @@ --- id: 587d7db5367417b2b2512b94 -title: Match Anything with Wildcard Period +title: 用通配符匹配任何内容 challengeType: 1 forumTopicId: 301348 dashedName: match-anything-with-wildcard-period @@ -8,72 +8,74 @@ dashedName: match-anything-with-wildcard-period # --description-- -Sometimes you won't (or don't need to) know the exact characters in your patterns. Thinking of all words that match, say, a misspelling would take a long time. Luckily, you can save time using the wildcard character: `.` +有时不(或不需要)知道匹配模式中的确切字符。 如果要精确匹配到完整的单词,那出现一个拼写错误就会匹配不到。 幸运的是,可以使用通配符 `.` 来处理这种情况。 -The wildcard character `.` will match any one character. The wildcard is also called `dot` and `period`. You can use the wildcard character just like any other character in the regex. For example, if you wanted to match `"hug"`, `"huh"`, `"hut"`, and `"hum"`, you can use the regex `/hu./` to match all four words. +通配符 `.` 将匹配任何一个字符。 通配符也叫 `dot` 或 `period`。 可以像使用正则表达式中任何其他字符一样使用通配符。 例如,如果想匹配 `hug`、`huh`、`hut` 和 `hum`,可以使用正则表达式 `/hu./` 匹配以上四个单词。 ```js let humStr = "I'll hum a song"; let hugStr = "Bear hug"; let huRegex = /hu./; -huRegex.test(humStr); // Returns true -huRegex.test(hugStr); // Returns true +huRegex.test(humStr); +huRegex.test(hugStr); ``` +上面的 `test` 都会返回 `true`。 + # --instructions-- -Complete the regex `unRegex` so that it matches the strings `"run"`, `"sun"`, `"fun"`, `"pun"`, `"nun"`, and `"bun"`. Your regex should use the wildcard character. +完成正则表达式 `unRegex` 以匹配字符串 `run`、`sun`、`fun`、`pun`、`nun` 和 `bun`。 正则表达式中应该使用通配符。 # --hints-- -You should use the `.test()` method. +你应该使用 `.test()` 方法。 ```js assert(code.match(/\.test\(.*\)/)); ``` -You should use the wildcard character in your regex `unRegex` +你应该在你的正则表达式 `unRegex` 中使用通配符。 ```js assert(/\./.test(unRegex.source)); ``` -Your regex `unRegex` should match `"run"` in `"Let us go on a run."` +你的正则表达式 `unRegex` 应该在字符串 `Let us go on a run.` 中匹配到 `run` 单词。 ```js unRegex.lastIndex = 0; assert(unRegex.test('Let us go on a run.')); ``` -Your regex `unRegex` should match `"sun"` in `"The sun is out today."` +你的正则表达式 `unRegex` 应该在字符串 `The sun is out today.` 中匹配到 `sun` 单词。 ```js unRegex.lastIndex = 0; assert(unRegex.test('The sun is out today.')); ``` -Your regex `unRegex` should match `"fun"` in `"Coding is a lot of fun."` +你的正则表达式 `unRegex` 应该在字符串 `Coding is a lot of fun.` 中匹配到 `fun` 单词。 ```js unRegex.lastIndex = 0; assert(unRegex.test('Coding is a lot of fun.')); ``` -Your regex `unRegex` should match `"pun"` in `"Seven days without a pun makes one weak."` +你的正则表达式 `unRegex` 应该在字符串 `Seven days without a pun makes one weak.` 中匹配到 `pun`单词。 ```js unRegex.lastIndex = 0; assert(unRegex.test('Seven days without a pun makes one weak.')); ``` -Your regex `unRegex` should match `"nun"` in `"One takes a vow to be a nun."` +你的正则表达式 `unRegex` 应该在字符串 `One takes a vow to be a nun.` 中匹配到 `nun` 单词。 ```js unRegex.lastIndex = 0; assert(unRegex.test('One takes a vow to be a nun.')); ``` -Your regex `unRegex` should match `"bun"` in `"She got fired from the hot dog stand for putting her hair in a bun."` +你的正则表达式 `unRegex` 应该在字符串 `She got fired from the hot dog stand for putting her hair in a bun.` 中匹配到 `bun` 单词。 ```js unRegex.lastIndex = 0; @@ -84,14 +86,14 @@ assert( ); ``` -Your regex `unRegex` should not match `"There is a bug in my code."` +你的正则表达式 `unRegex` 不应该匹配 `There is a bug in my code.`。 ```js unRegex.lastIndex = 0; assert(!unRegex.test('There is a bug in my code.')); ``` -Your regex `unRegex` should not match `"Catch me if you can."` +你的正则表达式 `unRegex` 不应该匹配 `Catch me if you can.`。 ```js unRegex.lastIndex = 0; diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-beginning-string-patterns.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-beginning-string-patterns.md index 099238eebf..08127c94e0 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-beginning-string-patterns.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-beginning-string-patterns.md @@ -1,6 +1,6 @@ --- id: 587d7db7367417b2b2512b9d -title: Match Beginning String Patterns +title: 匹配字符串的开头 challengeType: 1 forumTopicId: 301349 dashedName: match-beginning-string-patterns @@ -8,45 +8,45 @@ dashedName: match-beginning-string-patterns # --description-- -Prior challenges showed that regular expressions can be used to look for a number of matches. They are also used to search for patterns in specific positions in strings. +回顾一下之前的挑战,正则表达式可以用于查找多项匹配。 还可以查询字符串中符合指定匹配模式的字符。 -In an earlier challenge, you used the caret character (`^`) inside a character set to create a negated character set in the form `[^thingsThatWillNotBeMatched]`. Outside of a character set, the caret is used to search for patterns at the beginning of strings. +在之前的挑战中,使用字符集中前插入符号(`^`)来创建一个否定字符集,形如 `[^thingsThatWillNotBeMatched]`。 除了在字符集中使用之外,脱字符还用于匹配字符串的开始位置。 ```js let firstString = "Ricky is first and can be found."; let firstRegex = /^Ricky/; firstRegex.test(firstString); -// Returns true let notFirst = "You can't find Ricky now."; firstRegex.test(notFirst); -// Returns false ``` +第一次 `test` 调用将返回 `true`,而第二次调用将返回 `false`。 + # --instructions-- -Use the caret character in a regex to find `"Cal"` only in the beginning of the string `rickyAndCal`. +在正则表达式中使用脱字符来找到 `Cal` 在字符串 `rickyAndCal` 中的开始位置。 # --hints-- -Your regex should search for `"Cal"` with a capital letter. +你的正则表达式应该搜寻首字母大写的 `Cal`。 ```js assert(calRegex.source == '^Cal'); ``` -Your regex should not use any flags. +你的正则表达式不应该使用任何标志。 ```js assert(calRegex.flags == ''); ``` -Your regex should match `"Cal"` at the beginning of the string. +你的正则表达式应该匹配字符串 `Cal` 的开始位置。 ```js assert(calRegex.test('Cal and Ricky both like racing.')); ``` -Your regex should not match `"Cal"` in the middle of a string. +你的正则表达式不应该匹配中间包含 `Cal` 的字符串。 ```js assert(!calRegex.test('Ricky and Cal both like racing.')); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-one-or-more-times.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-one-or-more-times.md index cf54e942ff..5d8e90355d 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-one-or-more-times.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-one-or-more-times.md @@ -1,6 +1,6 @@ --- id: 587d7db6367417b2b2512b99 -title: Match Characters that Occur One or More Times +title: 匹配出现一次或多次的字符 challengeType: 1 forumTopicId: 301350 dashedName: match-characters-that-occur-one-or-more-times @@ -8,33 +8,33 @@ dashedName: match-characters-that-occur-one-or-more-times # --description-- -Sometimes, you need to match a character (or group of characters) that appears one or more times in a row. This means it occurs at least once, and may be repeated. +有时,需要匹配出现一次或者连续多次的的字符(或字符组)。 这意味着它至少出现一次,并且可能重复出现。 -You can use the `+` character to check if that is the case. Remember, the character or pattern has to be present consecutively. That is, the character has to repeat one after the other. +可以使用 `+` 符号来检查情况是否如此。 记住,字符或匹配模式必须一个接一个地连续出现。 这就是说,字符必须一个接一个地重复。 -For example, `/a+/g` would find one match in `"abc"` and return `["a"]`. Because of the `+`, it would also find a single match in `"aabc"` and return `["aa"]`. +例如,`/a+/g` 会在 `abc` 中匹配到一个匹配项,并且返回 `["a"]`。 因为 `+` 的存在,它也会在 `aabc` 中匹配到一个匹配项,然后返回 `["aa"]`。 -If it were instead checking the string `"abab"`, it would find two matches and return `["a", "a"]` because the `a` characters are not in a row - there is a `b` between them. Finally, since there is no `"a"` in the string `"bcd"`, it wouldn't find a match. +如果它是检查字符串 `abab`,它将匹配到两个匹配项并且返回`["a", "a"]`,因为`a`字符不连续,在它们之间有一个`b`字符。 最后,因为在字符串 `bcd` 中没有 `a`,因此找不到匹配项。 # --instructions-- -You want to find matches when the letter `s` occurs one or more times in `"Mississippi"`. Write a regex that uses the `+` sign. +想要在字符串 `Mississippi` 中匹配到出现一次或多次的字母 `s` 的匹配项。 编写一个使用 `+` 符号的正则表达式。 # --hints-- -Your regex `myRegex` should use the `+` sign to match one or more `s` characters. +你的正则表达式 `myRegex` 应该使用 `+` 符号来匹配一个或多个 `s` 字符。 ```js assert(/\+/.test(myRegex.source)); ``` -Your regex `myRegex` should match 2 items. +你的正则表达式 `myRegex` 应该匹配两项。 ```js assert(result.length == 2); ``` -The `result` variable should be an array with two matches of `"ss"` +`result` 变量应该是一个数组,两个匹配的 `ss` ```js assert(result[0] == 'ss' && result[1] == 'ss'); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-zero-or-more-times.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-zero-or-more-times.md index 745202e5fe..08199ee77e 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-zero-or-more-times.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-zero-or-more-times.md @@ -1,6 +1,6 @@ --- id: 587d7db6367417b2b2512b9a -title: Match Characters that Occur Zero or More Times +title: 匹配出现零次或多次的字符 challengeType: 1 forumTopicId: 301351 dashedName: match-characters-that-occur-zero-or-more-times @@ -8,51 +8,53 @@ dashedName: match-characters-that-occur-zero-or-more-times # --description-- -The last challenge used the plus `+` sign to look for characters that occur one or more times. There's also an option that matches characters that occur zero or more times. +上一次的挑战中使用了加号 `+` 来查找出现一次或多次的字符。 还有一个选项可以匹配出现零次或多次的字符。 -The character to do this is the asterisk or star: `*`. +执行该操作的字符叫做星号,即`*`。 ```js let soccerWord = "gooooooooal!"; let gPhrase = "gut feeling"; let oPhrase = "over the moon"; let goRegex = /go*/; -soccerWord.match(goRegex); // Returns ["goooooooo"] -gPhrase.match(goRegex); // Returns ["g"] -oPhrase.match(goRegex); // Returns null +soccerWord.match(goRegex); +gPhrase.match(goRegex); +oPhrase.match(goRegex); ``` +按顺序排列,三次 `match` 调用将返回值 `["goooooooo"]`,`["g"]` 和 `null`。 + # --instructions-- -For this challenge, `chewieQuote` has been initialized as "Aaaaaaaaaaaaaaaarrrgh!" behind the scenes. Create a regex `chewieRegex` that uses the `*` character to match an uppercase `"A"` character immediately followed by zero or more lowercase `"a"` characters in `chewieQuote`. Your regex does not need flags or character classes, and it should not match any of the other quotes. +在这个挑战里,`chewieQuote` 已经被初始化为 `Aaaaaaaaaaaaaaaarrrgh!`。 创建一个变量为 `chewieRegex` 的正则表达式,使用 `*` 在 `chewieQuote` 中匹配 `A` 及其之后出现的零个或多个`a`。 你的正则表达式不需要使用修饰符,也不需要匹配引号。 # --hints-- -Your regex `chewieRegex` should use the `*` character to match zero or more `a` characters. +你的正则表达式 `chewieRegex` 应该使用 `*` 字符来匹配零或更多的 `a` 字符。 ```js assert(/\*/.test(chewieRegex.source)); ``` -Your regex should match `"A"` in `chewieQuote`. +正则表达式应当匹配 `chewieQuote` 里的 `A`。 ```js assert(result[0][0] === 'A'); ``` -Your regex should match `"Aaaaaaaaaaaaaaaa"` in `chewieQuote`. +你的正则表达式应该与 `chewieQuote` 中的字符串 `Aaaaaaaaaaaaaaaa` 匹配。 ```js assert(result[0] === 'Aaaaaaaaaaaaaaaa'); ``` -Your regex `chewieRegex` should match 16 characters in `chewieQuote`. +你的正则表达式 `chewieRegex` 应该匹配 `chewieQuote` 中的 16 个字符。 ```js assert(result[0].length === 16); ``` -Your regex should not match any characters in "He made a fair move. Screaming about it can't help you." +你的正则表达式不应该有任何匹配,在字符 `He made a fair move. Screaming about it can't help you.` ```js assert( @@ -60,7 +62,7 @@ assert( ); ``` -Your regex should not match any characters in "Let him have it. It's not wise to upset a Wookiee." +你的正则表达式不应该有任何匹配,在字符 `Let him have it. It's not wise to upset a Wookiee.` ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-ending-string-patterns.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-ending-string-patterns.md index 60e1638ce7..49f91af819 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-ending-string-patterns.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-ending-string-patterns.md @@ -1,6 +1,6 @@ --- id: 587d7db7367417b2b2512b9e -title: Match Ending String Patterns +title: 匹配字符串的末尾 challengeType: 1 forumTopicId: 301352 dashedName: match-ending-string-patterns @@ -8,40 +8,39 @@ dashedName: match-ending-string-patterns # --description-- -In the last challenge, you learned to use the caret character to search for patterns at the beginning of strings. There is also a way to search for patterns at the end of strings. +在上一个挑战中,学习了使用脱字符号来搜寻字符串的开始位置。 还有一种方法可以搜寻字符串末尾的匹配模式。 -You can search the end of strings using the dollar sign character `$` at the end of the regex. +可以使用正则表达式的美元符号 `$` 来搜寻字符串的结尾。 ```js let theEnding = "This is a never ending story"; let storyRegex = /story$/; storyRegex.test(theEnding); -// Returns true let noEnding = "Sometimes a story will have to end"; storyRegex.test(noEnding); -// Returns false - ``` +第一次 `test` 调用将返回 `true`, 而第二次调用将返回 `false`。 + # --instructions-- -Use the anchor character (`$`) to match the string `"caboose"` at the end of the string `caboose`. +使用锚点字符 `$` 来匹配字符串 `caboose` 在字符串末尾 `caboose`。 # --hints-- -You should search for `"caboose"` with the dollar sign `$` anchor in your regex. +你应该在正则表达式使用美元符号 `$` 来搜寻 `caboose`。 ```js assert(lastRegex.source == 'caboose$'); ``` -Your regex should not use any flags. +你的正则表达式不应该使用任何标志。 ```js assert(lastRegex.flags == ''); ``` -You should match `"caboose"` at the end of the string `"The last car on a train is the caboose"` +你应该在字符串 `The last car on a train is the caboose` 的末尾匹配 `caboose`。 ```js assert(lastRegex.test('The last car on a train is the caboose')); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-everything-but-letters-and-numbers.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-everything-but-letters-and-numbers.md index 541817a663..7c8925e485 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-everything-but-letters-and-numbers.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-everything-but-letters-and-numbers.md @@ -1,6 +1,6 @@ --- id: 587d7db8367417b2b2512ba0 -title: Match Everything But Letters and Numbers +title: 匹配除了字母和数字的所有符号 challengeType: 1 forumTopicId: 301353 dashedName: match-everything-but-letters-and-numbers @@ -8,31 +8,33 @@ dashedName: match-everything-but-letters-and-numbers # --description-- -You've learned that you can use a shortcut to match alphanumerics `[A-Za-z0-9_]` using `\w`. A natural pattern you might want to search for is the opposite of alphanumerics. +已经了解到可以使用缩写 `\w` 来匹配字母和数字 `[A-Za-z0-9_]`。 不过,有可能想要搜寻的匹配模式是非字母数字字符。 -You can search for the opposite of the `\w` with `\W`. Note, the opposite pattern uses a capital letter. This shortcut is the same as `[^A-Za-z0-9_]`. +可以使用 `\W` 搜寻和 `\w` 相反的匹配模式。 注意,相反匹配模式使用大写字母。 此缩写与 `[^A-Za-z0-9_]` 是一样的。 ```js let shortHand = /\W/; let numbers = "42%"; let sentence = "Coding!"; -numbers.match(shortHand); // Returns ["%"] -sentence.match(shortHand); // Returns ["!"] +numbers.match(shortHand); +sentence.match(shortHand); ``` +第一次 `match` 调用将返回值 `["%"]` 而第二次调用将返回 `["!"]`。 + # --instructions-- -Use the shorthand character class `\W` to count the number of non-alphanumeric characters in various quotes and strings. +使用缩写 `\W` 来计算引号中所有非字符字母和数字字符的数量。 # --hints-- -Your regex should use the global flag. +你的正则表达式应该使用全局标识。 ```js assert(nonAlphabetRegex.global); ``` -Your regex should find 6 non-alphanumeric characters in `"The five boxing wizards jump quickly."`. +你的正则表达式应该在 `The five boxing wizards jump quickly.` 中匹配到 6 个非字母数字字符。 ```js assert( @@ -40,13 +42,13 @@ assert( ); ``` -Your regex should use the shorthand character to match characters which are non-alphanumeric. +正则表达式应该使用元字符来匹配非字母字符。 ```js assert(/\\W/.test(nonAlphabetRegex.source)); ``` -Your regex should find 8 non-alphanumeric characters in `"Pack my box with five dozen liquor jugs."` +你的正则表达式应该在 `Pack my box with five dozen liquor jugs.` 中匹配到 8 个非字母数字字符。 ```js assert( @@ -54,7 +56,7 @@ assert( ); ``` -Your regex should find 6 non-alphanumeric characters in `"How vexingly quick daft zebras jump!"` +你的正则表达式应该在 `How vexingly quick daft zebras jump!` 中匹配到 6 个非字母数字字符。 ```js assert( @@ -62,7 +64,7 @@ assert( ); ``` -Your regex should find 12 non-alphanumeric characters in `"123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ."` +你的正则表达式应该在字符串 `123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.` 中找到12个非字母数字字符。 ```js assert( diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-letters-of-the-alphabet.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-letters-of-the-alphabet.md index 7b48c2b89d..1c53af5f43 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-letters-of-the-alphabet.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-letters-of-the-alphabet.md @@ -1,6 +1,6 @@ --- id: 587d7db5367417b2b2512b96 -title: Match Letters of the Alphabet +title: 匹配字母表中的字母 challengeType: 1 forumTopicId: 301354 dashedName: match-letters-of-the-alphabet @@ -8,43 +8,45 @@ dashedName: match-letters-of-the-alphabet # --description-- -You saw how you can use character sets to specify a group of characters to match, but that's a lot of typing when you need to match a large range of characters (for example, every letter in the alphabet). Fortunately, there is a built-in feature that makes this short and simple. +了解了如何使用字符集(character sets)来指定要匹配的一组字符串,但是有时需要匹配大量字符(例如,字母表中的每个字母)。 有一种写法可以让实现这个功能变得简短。 -Inside a character set, you can define a range of characters to match using a hyphen character: `-`. +在字符集中,可以使用连字符(`-`)来定义要匹配的字符范围。 -For example, to match lowercase letters `a` through `e` you would use `[a-e]`. +例如,要匹配小写字母 `a` 到 `e`,你可以使用 `[a-e]`。 ```js let catStr = "cat"; let batStr = "bat"; let matStr = "mat"; let bgRegex = /[a-e]at/; -catStr.match(bgRegex); // Returns ["cat"] -batStr.match(bgRegex); // Returns ["bat"] -matStr.match(bgRegex); // Returns null +catStr.match(bgRegex); +batStr.match(bgRegex); +matStr.match(bgRegex); ``` +按顺序排列,三次 `match` 调用将返回值 `["cat"]`,`["bat"]` 和 `null`。 + # --instructions-- -Match all the letters in the string `quoteSample`. +匹配字符串 `quoteSample` 中的所有字母。 -**Note**: Be sure to match both uppercase and lowercase letters. +**注意**:一定要同时匹配大小写字母。 # --hints-- -Your regex `alphabetRegex` should match 35 items. +你的正则表达式 `alphabetRegex` 应该匹配 35 项。 ```js assert(result.length == 35); ``` -Your regex `alphabetRegex` should use the global flag. +你的正则表达式 `alphabetRegex` 应该使用全局标识。 ```js assert(alphabetRegex.flags.match(/g/).length == 1); ``` -Your regex `alphabetRegex` should use the case insensitive flag. +你的正则表达式 `alphabetRegex` 应该使用忽略大小写标志。 ```js assert(alphabetRegex.flags.match(/i/).length == 1); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-literal-strings.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-literal-strings.md index 132c48dbe4..aac3b2d092 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-literal-strings.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-literal-strings.md @@ -1,6 +1,6 @@ --- id: 587d7db3367417b2b2512b8f -title: Match Literal Strings +title: 匹配文字字符串 challengeType: 1 forumTopicId: 301355 dashedName: match-literal-strings @@ -8,44 +8,46 @@ dashedName: match-literal-strings # --description-- -In the last challenge, you searched for the word `"Hello"` using the regular expression `/Hello/`. That regex searched for a literal match of the string `"Hello"`. Here's another example searching for a literal match of the string `"Kevin"`: +在上一个挑战中,使用正则表达式 `/Hello/` 搜索到了字符串 `Hello`。 那个正则表达式在字符串中搜寻 `Hello` 的文字匹配。 下面是另一个在字符串中搜寻 `Kevin` 的示例: ```js let testStr = "Hello, my name is Kevin."; let testRegex = /Kevin/; testRegex.test(testStr); -// Returns true ``` -Any other forms of `"Kevin"` will not match. For example, the regex `/Kevin/` will not match `"kevin"` or `"KEVIN"`. +`test` 方法会返回 `true`。 + +任何其他形式的 `Kevin` 都不会被匹配。 例如,正则表达式 `/Kevin/` 不会匹配 `kevin` 或者`KEVIN`。 ```js let wrongRegex = /kevin/; wrongRegex.test(testStr); -// Returns false ``` -A future challenge will show how to match those other forms as well. +此 `test` 调用将返回 `false`。 + +后续的挑战将为你展示如何匹配其他形式的字符串。 # --instructions-- -Complete the regex `waldoRegex` to find `"Waldo"` in the string `waldoIsHiding` with a literal match. +完成正则表达式 `waldoRegex`,在字符串 `waldoIsHiding` 中匹配到文本 `"Waldo"`。 # --hints-- -Your regex `waldoRegex` should find `"Waldo"` +你的正则表达式 `waldoRegex` 应该匹配到 `Waldo`。 ```js assert(waldoRegex.test(waldoIsHiding)); ``` -Your regex `waldoRegex` should not search for anything else. +你的正则表达式 `waldoRegex` 不应该搜寻其他的任何内容。 ```js assert(!waldoRegex.test('Somewhere is hiding in this text.')); ``` -You should perform a literal string match with your regex. +你应该使用你的正则表达式对字符串执行文字匹配。 ```js assert(!/\/.*\/i/.test(code)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-non-whitespace-characters.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-non-whitespace-characters.md index 9607d58cc9..fe69b537dd 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-non-whitespace-characters.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-non-whitespace-characters.md @@ -1,6 +1,6 @@ --- id: 587d7db9367417b2b2512ba4 -title: Match Non-Whitespace Characters +title: 匹配非空白字符 challengeType: 1 forumTopicId: 18210 dashedName: match-non-whitespace-characters @@ -8,35 +8,37 @@ dashedName: match-non-whitespace-characters # --description-- -You learned about searching for whitespace using `\s`, with a lowercase `s`. You can also search for everything except whitespace. +已经学会了如何使用带有小写 `s` 的缩写 `\s` 来搜寻空白字符。 还可以搜寻除了空格之外的所有内容。 -Search for non-whitespace using `\S`, which is an uppercase `s`. This pattern will not match whitespace, carriage return, tab, form feed, and new line characters. You can think of it being similar to the character class `[^ \r\t\f\n\v]`. +使用 `\S` 搜寻非空白字符,其中 `s` 是大写。 此匹配模式将不匹配空格、回车符、制表符、换页符和换行符。 可以认为这类似于元字符 `[^ \r\t\f\n\v]`。 ```js let whiteSpace = "Whitespace. Whitespace everywhere!" let nonSpaceRegex = /\S/g; -whiteSpace.match(nonSpaceRegex).length; // Returns 32 +whiteSpace.match(nonSpaceRegex).length; ``` +返回值的 `.length` 应该是 `32`。 + # --instructions-- -Change the regex `countNonWhiteSpace` to look for multiple non-whitespace characters in a string. +修改正则表达式 `countNonWhiteSpace` 以查找字符串中的多个非空字符。 # --hints-- -Your regex should use the global flag. +您的正则表达式应该使用全局标识。 ```js assert(countNonWhiteSpace.global); ``` -Your regex should use the shorthand character `\S` to match all non-whitespace characters. +你的正则表达式应该使用简写字符 `\S` 来匹配所有非空白字符。 ```js assert(/\\S/.test(countNonWhiteSpace.source)); ``` -Your regex should find 35 non-spaces in `"Men are from Mars and women are from Venus."` +您的正则表达式应该在字符串 `Men are from Mars and women are from Venus.` 中找到 35 个非空格字符。 ```js assert( @@ -45,13 +47,13 @@ assert( ); ``` -Your regex should find 23 non-spaces in `"Space: the final frontier."` +你的正则表达式应该在 `Space: the final frontier.` 中匹配到 23 个非空白字符。 ```js assert('Space: the final frontier.'.match(countNonWhiteSpace).length == 23); ``` -Your regex should find 21 non-spaces in `"MindYourPersonalSpace"` +你的正则表达式应该在 `MindYourPersonalSpace` 中匹配到 21 个非空白字符。 ```js assert('MindYourPersonalSpace'.match(countNonWhiteSpace).length == 21); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-numbers-and-letters-of-the-alphabet.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-numbers-and-letters-of-the-alphabet.md index 1702acbad8..c9edb4d684 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-numbers-and-letters-of-the-alphabet.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-numbers-and-letters-of-the-alphabet.md @@ -1,6 +1,6 @@ --- id: 587d7db5367417b2b2512b97 -title: Match Numbers and Letters of the Alphabet +title: 匹配字母表中的数字和字母 challengeType: 1 forumTopicId: 301356 dashedName: match-numbers-and-letters-of-the-alphabet @@ -8,38 +8,37 @@ dashedName: match-numbers-and-letters-of-the-alphabet # --description-- -Using the hyphen (`-`) to match a range of characters is not limited to letters. It also works to match a range of numbers. +使用连字符(`-`)匹配字符范围并不仅限于字母。 它还可以匹配一系列数字。 -For example, `/[0-5]/` matches any number between `0` and `5`, including the `0` and `5`. +例如,`/[0-5]/` 匹配 `0` 和 `5` 之间的任意数字,包含 `0` 和 `5`。 -Also, it is possible to combine a range of letters and numbers in a single character set. +此外,还可以在单个字符集中组合一系列字母和数字。 ```js let jennyStr = "Jenny8675309"; let myRegex = /[a-z0-9]/ig; -// matches all letters and numbers in jennyStr jennyStr.match(myRegex); ``` # --instructions-- -Create a single regex that matches a range of letters between `h` and `s`, and a range of numbers between `2` and `6`. Remember to include the appropriate flags in the regex. +创建一个正则表达式,使其可以匹配 `h` 和 `s` 之间的一系列字母,以及 `2` 和 `6` 之间的一系列数字。 请记得在正则表达式中包含恰当的标志。 # --hints-- -Your regex `myRegex` should match 17 items. +你的正则表达式 `myRegex` 应该匹配 17 项。 ```js assert(result.length == 17); ``` -Your regex `myRegex` should use the global flag. +你的正则表达式 `myRegex` 应该使用全局标志。 ```js assert(myRegex.flags.match(/g/).length == 1); ``` -Your regex `myRegex` should use the case insensitive flag. +你的正则表达式 `myRegex` 应该使用忽略大小写的标志。 ```js assert(myRegex.flags.match(/i/).length == 1); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-single-character-with-multiple-possibilities.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-single-character-with-multiple-possibilities.md index 097ded3a04..6e20f47bd0 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-single-character-with-multiple-possibilities.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-single-character-with-multiple-possibilities.md @@ -1,6 +1,6 @@ --- id: 587d7db5367417b2b2512b95 -title: Match Single Character with Multiple Possibilities +title: 将单个字符与多种可能性匹配 challengeType: 1 forumTopicId: 301357 dashedName: match-single-character-with-multiple-possibilities @@ -8,11 +8,11 @@ dashedName: match-single-character-with-multiple-possibilities # --description-- -You learned how to match literal patterns (`/literal/`) and wildcard character (`/./`). Those are the extremes of regular expressions, where one finds exact matches and the other matches everything. There are options that are a balance between the two extremes. +已经了解了文字匹配模式(`/literal/`)和通配符(`/./`)。 这是正则表达式的两种极端情况,一种是精确匹配,而另一种则是匹配所有。 在这两种极端情况之间有一个平衡选项。 -You can search for a literal pattern with some flexibility with character classes. Character classes allow you to define a group of characters you wish to match by placing them inside square (`[` and `]`) brackets. +可以使用字符集 (character classes)更灵活的匹配字符。 可以把字符集放在方括号(`[` 和 `]`)之间来定义一组需要匹配的字符串。 -For example, you want to match `"bag"`, `"big"`, and `"bug"` but not `"bog"`. You can create the regex `/b[aiu]g/` to do this. The `[aiu]` is the character class that will only match the characters `"a"`, `"i"`, or `"u"`. +例如,如果想要匹配 `bag`、`big` 和 `bug`,但是不想匹配 `bog`。 可以创建正则表达式 `/b[aiu]g/` 来执行此操作。 `[aiu]` 是只匹配字符 `a`、`i` 或者 `u` 的字符集。 ```js let bigStr = "big"; @@ -20,46 +20,47 @@ let bagStr = "bag"; let bugStr = "bug"; let bogStr = "bog"; let bgRegex = /b[aiu]g/; -bigStr.match(bgRegex); // Returns ["big"] -bagStr.match(bgRegex); // Returns ["bag"] -bugStr.match(bgRegex); // Returns ["bug"] -bogStr.match(bgRegex); // Returns null +bigStr.match(bgRegex); +bagStr.match(bgRegex); +bugStr.match(bgRegex); +bogStr.match(bgRegex); ``` +按顺序排列,四次 `match` 调用将返回值 `["big"]`、`["bag"]`、`["bug"]` 和 `null`。 + # --instructions-- -Use a character class with vowels (`a`, `e`, `i`, `o`, `u`) in your regex `vowelRegex` to find all the vowels in the string `quoteSample`. +使用元音字符集(`a`、`e`、`i`、`o`、`u`)在正则表达式 `vowelRegex` 中匹配到字符串 `quoteSample` 中的所有元音。 -**Note** -Be sure to match both upper- and lowercase vowels. +**注意:**一定要同时匹配大小写元音。 # --hints-- -You should find all 25 vowels. +你应该匹配到所有25个元音。 ```js assert(result.length == 25); ``` -Your regex `vowelRegex` should use a character class. +你的正则表达式 `vowelRegex` 应该使用字符集。 ```js assert(/\[.*\]/.test(vowelRegex.source)); ``` -Your regex `vowelRegex` should use the global flag. +你的正则表达式 `vowelRegex` 应该使用全局标志。 ```js assert(vowelRegex.flags.match(/g/).length == 1); ``` -Your regex `vowelRegex` should use the case insensitive flag. +你的正则表达式 `vowelRegex` 应该使用忽略大小写标志。 ```js assert(vowelRegex.flags.match(/i/).length == 1); ``` -Your regex should not match any consonants. +你的正则表达式不应该匹配任何辅音。 ```js assert(!/[b-df-hj-np-tv-z]/gi.test(result.join())); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-single-characters-not-specified.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-single-characters-not-specified.md index a0f6672834..a9331bed1d 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-single-characters-not-specified.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-single-characters-not-specified.md @@ -1,6 +1,6 @@ --- id: 587d7db6367417b2b2512b98 -title: Match Single Characters Not Specified +title: 匹配单个未指定的字符 challengeType: 1 forumTopicId: 301358 dashedName: match-single-characters-not-specified @@ -8,31 +8,31 @@ dashedName: match-single-characters-not-specified # --description-- -So far, you have created a set of characters that you want to match, but you could also create a set of characters that you do not want to match. These types of character sets are called negated character sets. +到目前为止,已经创建了一个想要匹配的字符集合,但也可以创建一个不想匹配的字符集合。 这些类型的字符集称为否定字符集( negated character sets)。 -To create a negated character set, you place a caret character (`^`) after the opening bracket and before the characters you do not want to match. +要创建否定字符集,需要在开始括号后面和不想匹配的字符前面放置脱字符(即`^`)。 -For example, `/[^aeiou]/gi` matches all characters that are not a vowel. Note that characters like `.`, `!`, `[`, `@`, `/` and white space are matched - the negated vowel character set only excludes the vowel characters. +例如,`/[^aeiou]/gi` 匹配所有非元音字符。 注意,字符 `.`、`!`、`[`、`@`、`/` 和空白字符等也会被匹配,该否定字符集仅排除元音字符。 # --instructions-- -Create a single regex that matches all characters that are not a number or a vowel. Remember to include the appropriate flags in the regex. +创建一个匹配所有非数字或元音字符的正则表达式。 请记得在正则表达式中包含恰当的标志。 # --hints-- -Your regex `myRegex` should match 9 items. +你的正则表达式 `myRegex` 应该匹配 9 项。 ```js assert(result.length == 9); ``` -Your regex `myRegex` should use the global flag. +你的正则表达式 `myRegex` 应该使用全局标志。 ```js assert(myRegex.flags.match(/g/).length == 1); ``` -Your regex `myRegex` should use the case insensitive flag. +你的正则表达式 `myRegex` 应该使用忽略大小写标志。 ```js assert(myRegex.flags.match(/i/).length == 1); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-whitespace.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-whitespace.md index b59d501509..5e7298e6bf 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-whitespace.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-whitespace.md @@ -1,6 +1,6 @@ --- id: 587d7db8367417b2b2512ba3 -title: Match Whitespace +title: 匹配空白字符 challengeType: 1 forumTopicId: 301359 dashedName: match-whitespace @@ -8,36 +8,36 @@ dashedName: match-whitespace # --description-- -The challenges so far have covered matching letters of the alphabet and numbers. You can also match the whitespace or spaces between letters. +迄今为止的挑战包括匹配字母和数字。 还可以匹配字符之间的空格。 -You can search for whitespace using `\s`, which is a lowercase `s`. This pattern not only matches whitespace, but also carriage return, tab, form feed, and new line characters. You can think of it as similar to the character class `[ \r\t\f\n\v]`. +可以使用 `\s` 搜寻空格,其中 `s` 是小写。 此匹配模式将匹配空格、回车符、制表符、换页符和换行符。 可以认为这类似于元字符 `[ \r\t\f\n\v]`。 ```js let whiteSpace = "Whitespace. Whitespace everywhere!" let spaceRegex = /\s/g; whiteSpace.match(spaceRegex); -// Returns [" ", " "] ``` +这个 `match` 调用将返回 `[" ", " "]`。 # --instructions-- -Change the regex `countWhiteSpace` to look for multiple whitespace characters in a string. +修改正则表达式 `countWhiteSpace` 查找字符串中的多个空白字符。 # --hints-- -Your regex should use the global flag. +你的正则表达式应该使用全局标识。 ```js assert(countWhiteSpace.global); ``` -Your regex should use the shorthand character `\s` to match all whitespace characters. +正则表达式应该使用元字符 `\s` 匹配所有的空白。 ```js assert(/\\s/.test(countWhiteSpace.source)); ``` -Your regex should find eight spaces in `"Men are from Mars and women are from Venus."` +你的正则表达式应该在字符串 `Men are from Mars and women are from Venus.` 中找到 8 个非空格字符。 ```js assert( @@ -46,13 +46,13 @@ assert( ); ``` -Your regex should find three spaces in `"Space: the final frontier."` +你的正则表达式应该在 `Space: the final frontier.` 中匹配到 3 个非空白字符。 ```js assert('Space: the final frontier.'.match(countWhiteSpace).length == 3); ``` -Your regex should find no spaces in `"MindYourPersonalSpace"` +你的正则表达式在 `MindYourPersonalSpace` 中应该匹配不到空白字符。 ```js assert('MindYourPersonalSpace'.match(countWhiteSpace) == null); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/positive-and-negative-lookahead.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/positive-and-negative-lookahead.md index e7b4814726..9b1053b51f 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/positive-and-negative-lookahead.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/positive-and-negative-lookahead.md @@ -1,6 +1,6 @@ --- id: 587d7dba367417b2b2512ba9 -title: Positive and Negative Lookahead +title: 正向先行断言和负向先行断言 challengeType: 1 forumTopicId: 301360 dashedName: positive-and-negative-lookahead @@ -8,88 +8,90 @@ dashedName: positive-and-negative-lookahead # --description-- -Lookaheads are patterns that tell JavaScript to look-ahead in your string to check for patterns further along. This can be useful when you want to search for multiple patterns over the same string. +先行断言 (Lookaheads)是告诉 JavaScript 在字符串中向前查找的匹配模式。 当想要在同一个字符串上搜寻多个匹配模式时,这可能非常有用。 -There are two kinds of lookaheads: positive lookahead and negative lookahead. +有两种先行断言:正向先行断言(positive lookahead)和负向先行断言(negative lookahead)。 -A positive lookahead will look to make sure the element in the search pattern is there, but won't actually match it. A positive lookahead is used as `(?=...)` where the `...` is the required part that is not matched. +正向先行断言会查看并确保搜索匹配模式中的元素存在,但实际上并不匹配。 正向先行断言的用法是 `(?=...)`,其中 `...` 就是需要存在但不会被匹配的部分。 -On the other hand, a negative lookahead will look to make sure the element in the search pattern is not there. A negative lookahead is used as `(?!...)` where the `...` is the pattern that you do not want to be there. The rest of the pattern is returned if the negative lookahead part is not present. +另一方面,负向先行断言会查看并确保搜索匹配模式中的元素不存在。 负向先行断言的用法是 `(?!...)`,其中 `...` 是希望不存在的匹配模式。 如果负向先行断言部分不存在,将返回匹配模式的其余部分。 -Lookaheads are a bit confusing but some examples will help. +尽管先行断言有点儿令人困惑,但是这些示例会有所帮助。 ```js let quit = "qu"; let noquit = "qt"; let quRegex= /q(?=u)/; let qRegex = /q(?!u)/; -quit.match(quRegex); // Returns ["q"] -noquit.match(qRegex); // Returns ["q"] +quit.match(quRegex); +noquit.match(qRegex); ``` -A more practical use of lookaheads is to check two or more patterns in one string. Here is a (naively) simple password checker that looks for between 3 and 6 characters and at least one number: +这两次 `match` 调用都将返回 `["q"]`。 + +先行断言的更实际用途是检查一个字符串中的两个或更多匹配模式。 这里有一个简单的密码检查器,密码规则是 3 到 6 个字符且至少包含一个数字: ```js let password = "abc123"; let checkPass = /(?=\w{3,6})(?=\D*\d)/; -checkPass.test(password); // Returns true +checkPass.test(password); ``` # --instructions-- -Use lookaheads in the `pwRegex` to match passwords that are greater than 5 characters long, and have two consecutive digits. +在正则表达式 `pwRegex` 中使用先行断言以匹配大于 5 个字符且有两个连续数字的密码。 # --hints-- -Your regex should use two positive `lookaheads`. +你的正则表达式应该使用两个正向先行断言( `lookaheads`)。 ```js assert(pwRegex.source.match(/\(\?=.*?\)\(\?=.*?\)/) !== null); ``` -Your regex should not match `"astronaut"` +您的正则表达式不应匹配字符串 `astronaut` ```js assert(!pwRegex.test('astronaut')); ``` -Your regex should not match `"banan1"` +你的正则表达式不应匹配字符串 `banan1` ```js assert(!pwRegex.test('banan1')); ``` -Your regex should match `"bana12"` +你的正则表达式应该匹配字符串 `bana12` ```js assert(pwRegex.test('bana12')); ``` -Your regex should match `"abc123"` +你的正则表达式应该匹配字符串 `abc123` ```js assert(pwRegex.test('abc123')); ``` -Your regex should not match `"12345"` +你的正则表达式不应匹配字符串 `12345` ```js assert(!pwRegex.test('12345')); ``` -Your regex should match `"8pass99"` +你的正则表达式应该匹配字符串 `8pass99` ```js assert(pwRegex.test('8pass99')); ``` -Your regex should not match `"1a2bcde"` +你的正表达式不应匹配字符串 `1a2bcde` ```js assert(!pwRegex.test('1a2bcde')); ``` -Your regex should match `"astr1on11aut"` +你的正则表达式应该匹配字符串 `astr1on11aut` ```js assert(pwRegex.test('astr1on11aut')); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/remove-whitespace-from-start-and-end.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/remove-whitespace-from-start-and-end.md index 63496d7733..ceca43f2e7 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/remove-whitespace-from-start-and-end.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/remove-whitespace-from-start-and-end.md @@ -1,6 +1,6 @@ --- id: 587d7dbb367417b2b2512bac -title: Remove Whitespace from Start and End +title: 删除开头和结尾的空白 challengeType: 1 forumTopicId: 301362 dashedName: remove-whitespace-from-start-and-end @@ -8,29 +8,29 @@ dashedName: remove-whitespace-from-start-and-end # --description-- -Sometimes whitespace characters around strings are not wanted but are there. Typical processing of strings is to remove the whitespace at the start and end of it. +有时字符串周围存在的空白字符并不是必需的。 字符串的典型处理是删除字符串开头和结尾处的空格。 # --instructions-- -Write a regex and use the appropriate string methods to remove whitespace at the beginning and end of strings. +编写一个正则表达式并使用适当的字符串方法删除字符串开头和结尾的空格。 -**Note:** The `String.prototype.trim()` method would work here, but you'll need to complete this challenge using regular expressions. +**注意:** `String.prototype.trim()` 方法在这里也可以实现同样的效果,但是你需要使用正则表达式来完成此项挑战。 # --hints-- -`result` should equal to `"Hello, World!"` +`result` 应该等于 `Hello, World!` ```js assert(result == 'Hello, World!'); ``` -Your solution should not use the `String.prototype.trim()` method. +你不应该使用 `String.prototype.trim()` 方法。 ```js assert(!code.match(/\.?[\s\S]*?trim/)); ``` -The `result` variable should not be set equal to a string. +`result` 变量不应该设置为等于字符串。 ```js assert(!code.match(/result\s*=\s*".*?"/)); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/restrict-possible-usernames.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/restrict-possible-usernames.md index 59da9fb360..8ddca8ac3f 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/restrict-possible-usernames.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/restrict-possible-usernames.md @@ -1,6 +1,6 @@ --- id: 587d7db8367417b2b2512ba2 -title: Restrict Possible Usernames +title: 限制可能的用户名 challengeType: 1 forumTopicId: 301363 dashedName: restrict-possible-usernames @@ -8,96 +8,102 @@ dashedName: restrict-possible-usernames # --description-- -Usernames are used everywhere on the internet. They are what give users a unique identity on their favorite sites. +用户名在互联网上随处可见。 它们是用户在自己喜欢的网站上的唯一身份。 -You need to check all the usernames in a database. Here are some simple rules that users have to follow when creating their username. +需要检索数据库中的所有用户名。 以下是用户在创建用户名时必须遵守的一些简单规则。 -1) Usernames can only use alpha-numeric characters. +1) 用户名只能是数字字母字符。 -2) The only numbers in the username have to be at the end. There can be zero or more of them at the end. Username cannot start with the number. +2) 用户名中的数字必须在最后。 数字可以有零个或多个。 用户名不能以数字开头。 -3) Username letters can be lowercase and uppercase. +3) 用户名字母可以是小写字母和大写字母。 -4) Usernames have to be at least two characters long. A two-character username can only use alphabet letters as characters. +4) 用户名长度必须至少为两个字符。 两位用户名只能使用字母。 # --instructions-- -Change the regex `userCheck` to fit the constraints listed above. +修改正则表达式 `userCheck` 以满足上面列出的约束。 # --hints-- -Your regex should match `JACK` +你的正则表达式应该匹配字符串 `JACK` ```js assert(userCheck.test('JACK')); ``` -Your regex should not match `J` +你的正则表达式不应匹配字符串 `J` ```js assert(!userCheck.test('J')); ``` -Your regex should match `Jo` +你的正则表达式应该匹配字符串 `Jo` ```js assert(userCheck.test('Jo')); ``` -Your regex should match `Oceans11` +你的正则表达式应该匹配字符串 `Oceans11` ```js assert(userCheck.test('Oceans11')); ``` -Your regex should match `RegexGuru` +你的正则表达式应该匹配字符串 `RegexGuru` ```js assert(userCheck.test('RegexGuru')); ``` -Your regex should not match `007` +你的正则表达式不应匹配字符串 `007` ```js assert(!userCheck.test('007')); ``` -Your regex should not match `9` +你的正则表达式不应匹配字符串 `9` ```js assert(!userCheck.test('9')); ``` -Your regex should not match `A1` +你的正则表达式不应匹配字符串 `A1` ```js assert(!userCheck.test('A1')); ``` -Your regex should not match `BadUs3rnam3` +你的正则表达式不应匹配字符串 `BadUs3rnam3` ```js assert(!userCheck.test('BadUs3rnam3')); ``` -Your regex should match `Z97` +你的正则表达式应该匹配字符串 `Z97` ```js assert(userCheck.test('Z97')); ``` -Your regex should not match `c57bT3` +你的正则表达式不应匹配字符串 `c57bT3` ```js assert(!userCheck.test('c57bT3')); ``` -Your regex should match `AB1` +你的正则表达式应该匹配字符串 `AB1` ```js assert(userCheck.test('AB1')); ``` +你的正则表达式不应匹配字符串 `J%4` + +```js +assert(!userCheck.test('J%4')) +``` + # --seed-- ## --seed-contents-- diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/specify-exact-number-of-matches.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/specify-exact-number-of-matches.md index 8f7a68cc7b..b9edaaef6b 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/specify-exact-number-of-matches.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/specify-exact-number-of-matches.md @@ -1,6 +1,6 @@ --- id: 587d7db9367417b2b2512ba7 -title: Specify Exact Number of Matches +title: 指定匹配的确切数量 challengeType: 1 forumTopicId: 301365 dashedName: specify-exact-number-of-matches @@ -8,63 +8,65 @@ dashedName: specify-exact-number-of-matches # --description-- -You can specify the lower and upper number of patterns with quantity specifiers using curly brackets. Sometimes you only want a specific number of matches. +可以使用带有花括号的数量说明符来指定匹配模式的上下限。 但有时只需要特定数量的匹配。 -To specify a certain number of patterns, just have that one number between the curly brackets. +要指定一定数量的匹配模式,只需在大括号之间放置一个数字。 -For example, to match only the word `"hah"` with the letter `a` `3` times, your regex would be `/ha{3}h/`. +例如,要只匹配字母 `a` 出现 `3` 次的单词`hah`,正则表达式应为`/ha{3}h/`。 ```js let A4 = "haaaah"; let A3 = "haaah"; let A100 = "h" + "a".repeat(100) + "h"; let multipleHA = /ha{3}h/; -multipleHA.test(A4); // Returns false -multipleHA.test(A3); // Returns true -multipleHA.test(A100); // Returns false +multipleHA.test(A4); +multipleHA.test(A3); +multipleHA.test(A100); ``` +按顺序排列,三次 `test` 调用将返回值 `false`,`true` 和 `false`。 + # --instructions-- -Change the regex `timRegex` to match the word `"Timber"` only when it has four letter `m`'s. +修改正则表达式`timRegex`,以匹配仅有四个字母 `m` 的单词 `Timber`。 # --hints-- -Your regex should use curly brackets. +你的正则表达式应该使用花括号。 ```js assert(timRegex.source.match(/{.*?}/).length > 0); ``` -Your regex should not match `"Timber"` +你的正则表达式不应匹配字符串 `Timber` ```js timRegex.lastIndex = 0; assert(!timRegex.test('Timber')); ``` -Your regex should not match `"Timmber"` +你的正则表达式不应匹配字符串 `Timmber` ```js timRegex.lastIndex = 0; assert(!timRegex.test('Timmber')); ``` -Your regex should not match `"Timmmber"` +你的正则表达式不应匹配字符串 `Timmmber` ```js timRegex.lastIndex = 0; assert(!timRegex.test('Timmmber')); ``` -Your regex should match `"Timmmmber"` +你的正则表达式应该匹配字符串 `Timmmmber` ```js timRegex.lastIndex = 0; assert(timRegex.test('Timmmmber')); ``` -Your regex should not match `"Timber"` with 30 `m`'s in it. +你的正则表达式不应该匹配包含 30 个字母 `m` 的 `Timber`。 ```js timRegex.lastIndex = 0; diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/specify-only-the-lower-number-of-matches.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/specify-only-the-lower-number-of-matches.md index f75994614f..84d7ac7a27 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/specify-only-the-lower-number-of-matches.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/specify-only-the-lower-number-of-matches.md @@ -1,6 +1,6 @@ --- id: 587d7db9367417b2b2512ba6 -title: Specify Only the Lower Number of Matches +title: 只指定匹配的下限 challengeType: 1 forumTopicId: 301366 dashedName: specify-only-the-lower-number-of-matches @@ -8,65 +8,67 @@ dashedName: specify-only-the-lower-number-of-matches # --description-- -You can specify the lower and upper number of patterns with quantity specifiers using curly brackets. Sometimes you only want to specify the lower number of patterns with no upper limit. +可以使用带有花括号的数量说明符来指定匹配模式的上下限。 但有时候只想指定匹配模式的下限而不需要指定上限。 -To only specify the lower number of patterns, keep the first number followed by a comma. +为此,在第一个数字后面跟一个逗号即可。 -For example, to match only the string `"hah"` with the letter `a` appearing at least `3` times, your regex would be `/ha{3,}h/`. +例如,要匹配至少出现 `3` 次字母 `a` 的字符串 `hah`,正则表达式应该是 `/ha{3,}h/`。 ```js let A4 = "haaaah"; let A2 = "haah"; let A100 = "h" + "a".repeat(100) + "h"; let multipleA = /ha{3,}h/; -multipleA.test(A4); // Returns true -multipleA.test(A2); // Returns false -multipleA.test(A100); // Returns true +multipleA.test(A4); +multipleA.test(A2); +multipleA.test(A100); ``` +按顺序排列,三次 `test` 调用将返回值 `true`,`false` 和 `true`。 + # --instructions-- -Change the regex `haRegex` to match the word `"Hazzah"` only when it has four or more letter `z`'s. +修改正则表达式 `haRegex`,匹配包含四个或更多字母 `z` 的单词 `Hazzah`。 # --hints-- -Your regex should use curly brackets. +你的正则表达式应该使用花括号。 ```js assert(haRegex.source.match(/{.*?}/).length > 0); ``` -Your regex should not match `"Hazzah"` +你的正则表达式不应匹配字符串 `Hazzah` ```js assert(!haRegex.test('Hazzah')); ``` -Your regex should not match `"Hazzzah"` +你的正则表达式不应匹配字符串 `Hazzzah` ```js assert(!haRegex.test('Hazzzah')); ``` -Your regex should match `"Hazzzzah"` +你的正则表达式应该匹配字符串 `Hazzzzah` ```js assert('Hazzzzah'.match(haRegex)[0].length === 8); ``` -Your regex should match `"Hazzzzzah"` +你的正则表达式应该匹配字符串 `Hazzzzzah` ```js assert('Hazzzzzah'.match(haRegex)[0].length === 9); ``` -Your regex should match `"Hazzzzzzah"` +你的正则表达式应该匹配字符串 `Hazzzzzzah` ```js assert('Hazzzzzzah'.match(haRegex)[0].length === 10); ``` -Your regex should match `"Hazzah"` with 30 `z`'s in it. +你的正则表达式应该匹配包含 30 个字母 `z` 的 `Hazzah`。 ```js assert('Hazzzzzzzzzzzzzzzzzzzzzzzzzzzzzzah'.match(haRegex)[0].length === 34); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/specify-upper-and-lower-number-of-matches.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/specify-upper-and-lower-number-of-matches.md index 83ed14cecc..8072f405d7 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/specify-upper-and-lower-number-of-matches.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/specify-upper-and-lower-number-of-matches.md @@ -1,6 +1,6 @@ --- id: 587d7db9367417b2b2512ba5 -title: Specify Upper and Lower Number of Matches +title: 指定匹配的上限和下限 challengeType: 1 forumTopicId: 301367 dashedName: specify-upper-and-lower-number-of-matches @@ -8,63 +8,65 @@ dashedName: specify-upper-and-lower-number-of-matches # --description-- -Recall that you use the plus sign `+` to look for one or more characters and the asterisk `*` to look for zero or more characters. These are convenient but sometimes you want to match a certain range of patterns. +回想一下,使用加号 `+` 查找一个或多个字符,使用星号 `*` 查找零个或多个字符。 这些都很方便,但有时需要匹配一定范围的匹配模式。 -You can specify the lower and upper number of patterns with quantity specifiers. Quantity specifiers are used with curly brackets (`{` and `}`). You put two numbers between the curly brackets - for the lower and upper number of patterns. +可以使用数量说明符(quantity specifiers)指定匹配模式的上下限。 数量说明符与花括号(`{` 和 `}`)一起使用。 可以在花括号之间放两个数字,这两个数字代表匹配模式的上限和下限。 -For example, to match only the letter `a` appearing between `3` and `5` times in the string `"ah"`, your regex would be `/a{3,5}h/`. +例如,要匹配出现 `3` 到 `5` 次字母 `a` 的在字符串 `ah`,正则表达式应为`/a{3,5}h/`。 ```js let A4 = "aaaah"; let A2 = "aah"; let multipleA = /a{3,5}h/; -multipleA.test(A4); // Returns true -multipleA.test(A2); // Returns false +multipleA.test(A4); +multipleA.test(A2); ``` +第一次 `test` 调用将返回 `true`,而第二次调用将返回 `false`。 + # --instructions-- -Change the regex `ohRegex` to match the entire phrase `"Oh no"` only when it has `3` to `6` letter `h`'s. +修改正则表达式 `ohRegex` 以匹配出现 `3` 到 `6` 次字母 `h` 的字符串 `Oh no`。 # --hints-- -Your regex should use curly brackets. +你的正则表达式应该使用花括号。 ```js assert(ohRegex.source.match(/{.*?}/).length > 0); ``` -Your regex should not match `"Ohh no"` +你的正则表达式不应匹配字符串 `Ohh no` ```js assert(!ohRegex.test('Ohh no')); ``` -Your regex should match `"Ohhh no"` +你的正则表达式应该匹配字符串 `Ohhh no` ```js assert('Ohhh no'.match(ohRegex)[0].length === 7); ``` -Your regex should match `"Ohhhh no"` +你的正则表达式应该匹配字符串 `Ohhhh no` ```js assert('Ohhhh no'.match(ohRegex)[0].length === 8); ``` -Your regex should match `"Ohhhhh no"` +你的正则表达式应该匹配字符串 `Ohhhhh no` ```js assert('Ohhhhh no'.match(ohRegex)[0].length === 9); ``` -Your regex should match `"Ohhhhhh no"` +你的正则表达式应该匹配字符串 `Ohhhhhh no` ```js assert('Ohhhhhh no'.match(ohRegex)[0].length === 10); ``` -Your regex should not match `"Ohhhhhhh no"` +你的正则表达式应该匹配字符串 `Ohhhhhhh no` ```js assert(!ohRegex.test('Ohhhhhhh no')); diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/use-capture-groups-to-search-and-replace.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/use-capture-groups-to-search-and-replace.md index d7d2771dae..27b8bcb924 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/use-capture-groups-to-search-and-replace.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/use-capture-groups-to-search-and-replace.md @@ -1,6 +1,6 @@ --- id: 587d7dbb367417b2b2512bab -title: Use Capture Groups to Search and Replace +title: 使用捕获组搜索和替换 challengeType: 1 forumTopicId: 301368 dashedName: use-capture-groups-to-search-and-replace @@ -8,55 +8,57 @@ dashedName: use-capture-groups-to-search-and-replace # --description-- -Searching is useful. However, you can make searching even more powerful when it also changes (or replaces) the text you match. +搜索功能是很有用的。 但是,当搜索同时也执行更改(或替换)匹配文本的操作时,搜索功能就会显得更加强大。 -You can search and replace text in a string using `.replace()` on a string. The inputs for `.replace()` is first the regex pattern you want to search for. The second parameter is the string to replace the match or a function to do something. +可以在字符串上使用 `.replace()` 方法来搜索并替换字符串中的文本。 `.replace()` 的输入首先是想要搜索的正则表达式匹配模式。 第二个参数是用于替换匹配的字符串或用于执行某些操作的函数。 ```js let wrongText = "The sky is silver."; let silverRegex = /silver/; wrongText.replace(silverRegex, "blue"); -// Returns "The sky is blue." ``` -You can also access capture groups in the replacement string with dollar signs (`$`). +`replace` 调用将返回字符串 `The sky is blue.`。 + +你还可以使用美元符号(`$`)访问替换字符串中的捕获组。 ```js "Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1'); -// Returns "Camp Code" ``` +调用 `replace` 将返回字符串 `Camp Code`。 + # --instructions-- -Write a regex `fixRegex` using three capture groups that will search for each word in the string "one two three". Then update the `replaceText` variable to replace "one two three" with the string "three two one" and assign the result to the `result` variable. Make sure you are utilizing capture groups in the replacement string using the dollar sign (`$`) syntax. +使用三个捕获组编写一个正则表达式 `fixRegex`,这三个捕获组将搜索字符串 `one two three` 中的每个单词。 然后更新 `replaceText` 变量,以字符串 `three two one` 替换 `one two three`,并将结果分配给 `result` 变量。 确保使用美元符号(`$`)语法在替换字符串中使用捕获组。 # --hints-- -You should use `.replace()` to search and replace. +你应该使用 `.replace()` 搜索并替换。 ```js assert(code.match(/\.replace\(.*\)/)); ``` -Your regex should change `"one two three"` to `"three two one"` +你的正则表达式应该将字符串 `one two three` 更改为字符串 `three two one` ```js assert(result === 'three two one'); ``` -You should not change the last line. +你不应该改变最后一行。 ```js assert(code.match(/result\s*=\s*str\.replace\(.*?\)/)); ``` -`fixRegex` should use at least three capture groups. +`fixRegex` 应该至少使用三个抓取组。 ```js assert(new RegExp(fixRegex.source + '|').exec('').length - 1 >= 3); ``` -`replaceText` should use parenthesized submatch string(s) (i.e. the nth parenthesized submatch string, $n, corresponds to the nth capture group). +`replaceText` 应该使用括号化的子匹配字符串(例如:nth 括号化的子匹配字符串, $n, 对应于第 n 个捕获组)。 ```js { diff --git a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/using-the-test-method.md b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/using-the-test-method.md index e39467f661..f4f4f51029 100644 --- a/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/using-the-test-method.md +++ b/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/using-the-test-method.md @@ -1,6 +1,6 @@ --- id: 587d7db3367417b2b2512b8e -title: Using the Test Method +title: 使用测试方法 challengeType: 1 forumTopicId: 301369 dashedName: using-the-test-method @@ -8,32 +8,33 @@ dashedName: using-the-test-method # --description-- -Regular expressions are used in programming languages to match parts of strings. You create patterns to help you do that matching. +在编程语言中,正则表达式用于匹配指定的字符串。 通过正则表达式创建匹配模式(规则)可以帮你完成指定匹配。 -If you want to find the word `"the"` in the string `"The dog chased the cat"`, you could use the following regular expression: `/the/`. Notice that quote marks are not required within the regular expression. +如果想要在字符串 `The dog chased the cat` 中匹配到 `the` 这个单词,可以使用如下正则表达式:`/the/`。 注意,正则表达式中不需要引号。 -JavaScript has multiple ways to use regexes. One way to test a regex is using the `.test()` method. The `.test()` method takes the regex, applies it to a string (which is placed inside the parentheses), and returns `true` or `false` if your pattern finds something or not. +JavaScript 中有多种使用正则表达式的方法。 测试正则表达式的一种方法是使用 `.test()` 方法。 `.test()` 方法会把编写的正则表达式和字符串(即括号内的内容)匹配,如果成功匹配到字符,则返回 `true`,反之,返回 `false`。 ```js let testStr = "freeCodeCamp"; let testRegex = /Code/; testRegex.test(testStr); -// Returns true ``` +`test` 方法会返回 `true`。 + # --instructions-- -Apply the regex `myRegex` on the string `myString` using the `.test()` method. +使用 `.test()` 方法,检测字符串 `myString` 是否符合正则表达式 `myRegex` 定义的规则。 # --hints-- -You should use `.test()` to test the regex. +你应该使用 `.test()` 方法来检测正则表达式。 ```js assert(code.match(/myRegex.test\(\s*myString\s*\)/)); ``` -Your result should return `true`. +你的返回结果应该为 `true`。 ```js assert(result === true); diff --git a/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-25-5-clock.md b/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-25-5-clock.md index 2c66d0e2c7..d699ebc7e2 100644 --- a/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-25-5-clock.md +++ b/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-25-5-clock.md @@ -70,7 +70,7 @@ dashedName: build-a-25--5-clock **需求 28:** 当点击 id 属性为 `reset` 的元素时,id 属性为 `beep` 的音频元素必须停止播放并回到开头。 -你可以 fork [这个 CodePen 项目](https://codepen.io/freeCodeCamp/pen/MJjpwO) 来构建你的项目。 或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 +你可以使用这个 CodePen 模板,点击 `Save` 即可创建你自己的项目。 或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 当你完成了本项目,并且该项目所有测试运行通过, 请提交项目的 URL。 diff --git a/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-drum-machine.md b/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-drum-machine.md index 84c867e2c7..cab65e9c06 100644 --- a/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-drum-machine.md +++ b/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-drum-machine.md @@ -28,7 +28,7 @@ dashedName: build-a-drum-machine **需求 7:** 当触发一个具有 `.drum-pad` 属性的元素时,`#display` 元素内应该展示这个触发元素关联音频片段的描述字符串(每一个字符串都应该是独一无二的)。 -可以 fork [这个 CodePen 项目](https://codepen.io/freeCodeCamp/pen/MJjpwO) 来构建你的项目。 或者可以在任何喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 +你可以使用这个 CodePen 模板,点击 `Save` 即可创建你自己的项目。 或者可以在任何喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 当你完成了本项目,并且该项目所有测试运行通过,请提交项目的 URL。 diff --git a/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-javascript-calculator.md b/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-javascript-calculator.md index ac4bda19ea..15a8faeaf4 100644 --- a/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-javascript-calculator.md +++ b/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-javascript-calculator.md @@ -51,7 +51,7 @@ dashedName: build-a-javascript-calculator - **立即执行逻辑:** `11.5` - **公式/表达式逻辑:** `32.5` -可以 fork [这个 CodePen 项目](https://codepen.io/freeCodeCamp/pen/MJjpwO) 来构建项目。 或者可以在任何喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 +你可以使用这个 CodePen 模板,点击 `Save` 即可创建你自己的项目。 或者可以在任何喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 当你完成了本项目,并且该项目所有测试运行通过,请提交项目的 URL。 diff --git a/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-markdown-previewer.md b/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-markdown-previewer.md index f6ebccfe79..1cbe3ea179 100644 --- a/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-markdown-previewer.md +++ b/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-markdown-previewer.md @@ -28,7 +28,7 @@ dashedName: build-a-markdown-previewer **可选需求(你无需通过这项测试):** Markdown 预览器能够解析回车符并且将他们以 `br`(换行)元素的形式渲染出来。 -可以 fork [这个 CodePen 项目](https://codepen.io/freeCodeCamp/pen/MJjpwO) 来构建项目。 或者可以在任何喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 +你可以使用这个 CodePen 模板,点击 `Save` 即可创建你自己的项目。 或者可以在任何喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 当你完成了本项目,并且该项目所有测试运行通过,请提交项目的 URL。 diff --git a/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-random-quote-machine.md b/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-random-quote-machine.md index b2b62f3b8b..bda9fa92c2 100644 --- a/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-random-quote-machine.md +++ b/curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-random-quote-machine.md @@ -36,7 +36,7 @@ dashedName: build-a-random-quote-machine **需求 11:** 具有 `#quote-box` 属性的包裹元素应该水平居中。 请在浏览器缩放尺寸为 100% 且页面窗口最大化时运行测试。 -可以 fork [这个 CodePen 项目](https://codepen.io/freeCodeCamp/pen/MJjpwO)来构建项目。 或者可以在任何喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 +你可以使用这个 CodePen 模板,点击 `Save` 创建即可你自己的项目 或者可以在任何喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 一旦完成了本项目并且该项目所有测试运行通过,请提交项目的 URL。 diff --git a/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-bar-chart.md b/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-bar-chart.md index b0b3ea2de8..f5af9136f9 100644 --- a/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-bar-chart.md +++ b/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-bar-chart.md @@ -42,7 +42,7 @@ dashedName: visualize-data-with-a-bar-chart 以下是完成此项目所需的数据: `https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json` -你可以 fork [这个 CodePen pen 项目](https://codepen.io/freeCodeCamp/pen/MJjpwO)来构建你的项目。 或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`. +你可以使用 CodePen 模板来创建你的项目,点击 `Save` 即可创建你的项目。 或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`. 当你完成了本项目,并且该项目所有测试运行通过,请提交项目的 URL。 diff --git a/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-choropleth-map.md b/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-choropleth-map.md index e8df9c9f5f..a95e8b336c 100644 --- a/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-choropleth-map.md +++ b/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-choropleth-map.md @@ -41,7 +41,7 @@ dashedName: visualize-data-with-a-choropleth-map - **US Education Data:** `https://cdn.freecodecamp.org/testable-projects-fcc/data/choropleth_map/for_user_education.json` - **US County Data:** `https://cdn.freecodecamp.org/testable-projects-fcc/data/choropleth_map/counties.json` -你可以 fork [这个 CodePen 项目](https://codepen.io/freeCodeCamp/pen/MJjpwO)来构建你的项目。 或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`. +你可以使用 CodePen 模板来创建你的项目,点击 `Save` 即可创建你的项目。 或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`. 当你完成了本项目,并且该项目所有测试运行通过,请提交项目的 URL。 diff --git a/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-heat-map.md b/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-heat-map.md index 1700b3dfd7..061d24fac8 100644 --- a/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-heat-map.md +++ b/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-heat-map.md @@ -50,7 +50,7 @@ dashedName: visualize-data-with-a-heat-map 以下是完成此项目所需的数据:`https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/global-temperature.json` -你可以 fork [这个 CodePen 项目](https://codepen.io/freeCodeCamp/pen/MJjpwO)来构建你的项目。 或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`. +你可以使用这个 CodePen 模板来创建你的项目,点击 `Save` 即可创建你的项目。 或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`. 当你完成了本项目,并且该项目所有测试运行通过,请提交项目的 URL。 diff --git a/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-scatterplot-graph.md b/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-scatterplot-graph.md index 098786f154..e8d5b6027e 100644 --- a/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-scatterplot-graph.md +++ b/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-scatterplot-graph.md @@ -46,7 +46,7 @@ dashedName: visualize-data-with-a-scatterplot-graph 以下是完成此项目所需的数据:`https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/cyclist-data.json` -你可以 fork [这个 CodePen 项目](https://codepen.io/freeCodeCamp/pen/MJjpwO)来构建你的项目。 或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`. +你可以使用这个 CodePen 模板来创建你的项目,点击 `Save` 即可创建你的项目。 或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`. 当你完成了本项目,并且项目通过所有测试,请提交项目的 URL。 diff --git a/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-treemap-diagram.md b/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-treemap-diagram.md index c024557ada..293ecf91c1 100644 --- a/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-treemap-diagram.md +++ b/curriculum/challenges/chinese/04-data-visualization/data-visualization-projects/visualize-data-with-a-treemap-diagram.md @@ -42,7 +42,7 @@ dashedName: visualize-data-with-a-treemap-diagram - **Movie Sales:** `https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/movie-data.json` - **Video Game Sales:** `https://cdn.freecodecamp.org/testable-projects-fcc/data/tree_map/video-game-sales-data.json` -你可以 fork [这个 CodePen 项目](https://codepen.io/freeCodeCamp/pen/MJjpwO)来构建你的项目。 或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`. +你可以使用 CodePen 模板来创建你的项目,点击 `Save` 即可创建你的项目。 或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`. 当你完成了本项目,并且该项目所有测试运行通过,请提交项目的 URL。 diff --git a/curriculum/challenges/espanol/01-responsive-web-design/basic-html-and-html5/nest-an-anchor-element-within-a-paragraph.md b/curriculum/challenges/espanol/01-responsive-web-design/basic-html-and-html5/nest-an-anchor-element-within-a-paragraph.md index f02e326126..26d6f2f1df 100644 --- a/curriculum/challenges/espanol/01-responsive-web-design/basic-html-and-html5/nest-an-anchor-element-within-a-paragraph.md +++ b/curriculum/challenges/espanol/01-responsive-web-design/basic-html-and-html5/nest-an-anchor-element-within-a-paragraph.md @@ -29,7 +29,7 @@ A continuación está el elemento *anchor* `` (que requiere una etiqueta de c ` ... ` -El texto, `link to freecodecamp.org`, dentro de un elemento `a` se llama `anchor text`, y mostrará el enlace para hacer clic: +El texto, `link to freecodecamp.org`, dentro de un elemento `a` se llama anchor text, y mostrará el enlace para hacer clic: `link to freecodecamp.org` @@ -43,11 +43,19 @@ Anida el elemento `a` existente dentro de un nuevo elemento `p`. El nuevo párra # --hints-- -Debes tener un elemento `a` que enlace a "`https://freecatphotoapp.com`". +Solo debes tener un elemento `a`. ```js assert( - $('a[href="https://freecatphotoapp.com"]').length > 0 + $('a').length === 1 +); +``` + +El elemento `a` debe enlazar a "`https://freecatphotoapp.com`". + +```js +assert( + $('a[href="https://freecatphotoapp.com"]').length === 1 ); ``` @@ -61,13 +69,13 @@ assert( ); ``` -Debes crear un nuevo elemento `p` alrededor de tu elemento `a`. Debe haber al menos 3 etiquetas `p` en tu código HTML. +Debes crear un nuevo elemento `p`. Debe haber al menos 3 etiquetas `p` en tu código HTML. ```js assert($('p') && $('p').length > 2); ``` -Tu elemento `a` debe ser anidado dentro de tu nuevo elemento `p`. +El elemento `a` debe estar anidado dentro del nuevo elemento `p`. ```js assert( @@ -75,7 +83,7 @@ assert( ); ``` -Tu elemento `p` debe contener el texto `View more` (con un espacio después de él). +El elemento `p` debe contener el texto `View more` (con un espacio después de él). ```js assert( @@ -86,7 +94,7 @@ assert( ); ``` -Tu elemento `a` no debe tener el texto `View more`. +El elemento `a` no debe tener el texto `View more`. ```js assert( @@ -96,7 +104,7 @@ assert( ); ``` -Cada uno de tus elementos `p` debe tener una etiqueta de cierre. +Cada uno de los elementos `p` debe tener una etiqueta de cierre. ```js assert( @@ -106,7 +114,7 @@ assert( ); ``` -Cada uno de tus elementos `a` debe tener una etiqueta de cierre. +Cada uno de los elementos `a` debe tener una etiqueta de cierre. ```js assert( diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/import-a-default-export.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/import-a-default-export.md index d8a0a3d465..c7b1c70fda 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/import-a-default-export.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/import-a-default-export.md @@ -1,6 +1,6 @@ --- id: 587d7b8d367417b2b2512b59 -title: Import a Default Export +title: Importa una exportación por defecto challengeType: 1 forumTopicId: 301205 dashedName: import-a-default-export @@ -8,21 +8,21 @@ dashedName: import-a-default-export # --description-- -In the last challenge, you learned about `export default` and its uses. To import a default export, you need to use a different `import` syntax. In the following example, `add` is the default export of the `math_functions.js` file. Here is how to import it: +En el último desafío, aprendiste sobre `export default` (exportación por defecto) y sus usos. Para importar una exportación por defecto, necesita utilizar la sintaxis `import` de manera diferente. En el siguiente ejemplo, `add` es la exportación por defecto del archivo `math_functions.js`. A continuación, cómo importarlo: ```js import add from "./math_functions.js"; ``` -The syntax differs in one key place. The imported value, `add`, is not surrounded by curly braces (`{}`). `add` here is simply a variable name for whatever the default export of the `math_functions.js` file is. You can use any name here when importing a default. +La sintaxis difiere en un punto clave. El valor importado, `add`, no está rodeado por llaves (`{}`). `add`, aquí es simplemente un nombre de variable, para cualquiera que sea la exportación por defecto del archivo `math_functions.js`. Puedes utilizar cualquier nombre aquí, al importar un valor por defecto. # --instructions-- -In the following code, import the default export from the `math_functions.js` file, found in the same directory as this file. Give the import the name `subtract`. +El siguiente código, importa como exportación por defecto, desde el archivo `math_functions.js`, encontrado en el mismo directorio que este archivo. Da a la importación el nombre de `subtract`. # --hints-- -You should properly import `subtract` from `math_functions.js`. +Debes importar correctamente `subtract` de `math_functions.js`. ```js assert(code.match(/import\s+subtract\s+from\s+('|")\.\/math_functions\.js\1/g)); diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/reuse-javascript-code-using-import.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/reuse-javascript-code-using-import.md index ff3449dd2f..24ac03bf3b 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/reuse-javascript-code-using-import.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/reuse-javascript-code-using-import.md @@ -1,6 +1,6 @@ --- id: 587d7b8c367417b2b2512b55 -title: Reuse JavaScript Code Using import +title: Reutiliza código de JavaScript utilizando import challengeType: 1 forumTopicId: 301208 dashedName: reuse-javascript-code-using-import @@ -8,15 +8,15 @@ dashedName: reuse-javascript-code-using-import # --description-- -`import` allows you to choose which parts of a file or module to load. In the previous lesson, the examples exported `add` from the `math_functions.js` file. Here's how you can import it to use in another file: +`import` te permite elegir qué partes de un archivo o módulo cargar. En la lección previa, los ejemplos exportaron `add` del archivo `math_functions.js`. Así es como puedes importarlo para utilizarlo en otro archivo: ```js import { add } from './math_functions.js'; ``` -Here, `import` will find `add` in `math_functions.js`, import just that function for you to use, and ignore the rest. The `./` tells the import to look for the `math_functions.js` file in the same folder as the current file. The relative file path (`./`) and file extension (`.js`) are required when using import in this way. +Aquí, `import` encontrará `add` en `math_functions.js`, importa sólo esa función para que la uses, e ignora el resto. El `./`, dice a import que busque el archivo `math_functions.js` en la misma carpeta que el archivo actual. La ruta relativa del archivo (`./`) y la extensión del archivo (`.js`), son requeridos cuando se utiliza import de esta manera. -You can import more than one item from the file by adding them in the `import` statement like this: +Puedes importar más de un elemento del archivo, añadiéndolos en la declaración `import` de esta manera: ```js import { add, subtract } from './math_functions.js'; @@ -24,11 +24,11 @@ import { add, subtract } from './math_functions.js'; # --instructions-- -Add the appropriate `import` statement that will allow the current file to use the `uppercaseString` and `lowercaseString` functions you exported in the previous lesson. These functions are in a file called `string_functions.js`, which is in the same directory as the current file. +Agrega la declaración `import` apropiada que permita al archivo actual, usar las funciones `uppercaseString` y `lowercaseString` que exportaste de la lección previa. Estas funciones se encuentran en un archivo llamado `string_functions.js`, el cual está en el mismo directorio que el archivo actual. # --hints-- -You should properly import `uppercaseString`. +Debes importar `uppercaseString` apropiadamente. ```js assert( @@ -38,7 +38,7 @@ assert( ); ``` -You should properly import `lowercaseString`. +Debes importar `lowercaseString` apropiadamente. ```js assert( diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/use--to-import-everything-from-a-file.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/use--to-import-everything-from-a-file.md index a175f32383..3077294494 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/use--to-import-everything-from-a-file.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/use--to-import-everything-from-a-file.md @@ -1,6 +1,6 @@ --- id: 587d7b8c367417b2b2512b57 -title: Use * to Import Everything from a File +title: Use * para importar todo de un archivo challengeType: 1 forumTopicId: 301210 dashedName: use--to-import-everything-from-a-file @@ -8,13 +8,13 @@ dashedName: use--to-import-everything-from-a-file # --description-- -Suppose you have a file and you wish to import all of its contents into the current file. This can be done with the `import * as` syntax. Here's an example where the contents of a file named `math_functions.js` are imported into a file in the same directory: +Supongamos que tienes un archivo y deseas importar todo su contenido en el archivo actual. Esto puede hacerse con la sintaxis `import * as`. Este es un ejemplo donde los contenidos de un archivo llamado `math_functions.js` son importados a un archivo dentro del mismo directorio: ```js import * as myMathModule from "./math_functions.js"; ``` -The above `import` statement will create an object called `myMathModule`. This is just a variable name, you can name it anything. The object will contain all of the exports from `math_functions.js` in it, so you can access the functions like you would any other object property. Here's how you can use the `add` and `subtract` functions that were imported: +La anterior declaración `import`, crea un objeto llamado `myMathModule`. Esto es, sólo el nombre de una variable, puedes nombrarlo de cualquier manera. El objeto contiene todas las exportaciones de `math_functions.js`, así puedes acceder a las funciones, como haces con cualquier propiedad del objeto. A continuación puedes usar las funciones importadas `add` y `subtract`: ```js myMathModule.add(2,3); @@ -23,11 +23,11 @@ myMathModule.subtract(5,3); # --instructions-- -The code in this file requires the contents of the file: `string_functions.js`, that is in the same directory as the current file. Use the `import * as` syntax to import everything from the file into an object called `stringFunctions`. +El código actual, requiere los contenidos del archivo: `string_functions.js`, ubicado en el mismo directorio que el archivo actual. Usa la sintaxis `import * as`, para importar todo del archivo, en un objeto llamado `stringFunctions`. # --hints-- -Your code should properly use `import * as` syntax. +Tu código debe utilizar apropiadamente la sintaxis `import * as`. ```js assert(