chore(i8n,curriculum): processed translations (#41490)
Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
This commit is contained in:
@ -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');
|
||||
|
@ -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(
|
||||
|
@ -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--
|
||||
|
@ -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
|
||||
<script type="module" src="filename.js"></script>
|
||||
```
|
||||
|
||||
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(
|
||||
|
@ -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 <dfn>named export</dfn>. This allowed you to make multiple functions and variables available for use in other files.
|
||||
在 `export` 的课程中,你学习了<dfn>命名导出</dfn>语法, 这可以在其他文件中引用一些函数或者变量。
|
||||
|
||||
There is another `export` syntax you need to know, known as <dfn>export default</dfn>. 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.
|
||||
还需要了解另外一种被称为<dfn>默认导出</dfn>的 `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(
|
||||
|
@ -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 <dfn>template literal</dfn>. 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) =>
|
||||
|
@ -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) =>
|
||||
|
@ -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!');
|
||||
|
@ -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(
|
||||
|
@ -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(
|
||||
|
@ -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));
|
||||
|
@ -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]);
|
||||
|
@ -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);
|
||||
|
@ -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(
|
||||
|
@ -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 <dfn>default parameters</dfn> for functions.
|
||||
ES6 里允许给函数传入<dfn>默认参数</dfn>,来构建更加灵活的函数。
|
||||
|
||||
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));
|
||||
|
@ -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(
|
||||
|
@ -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));
|
||||
|
@ -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 <dfn>class</dfn> keyword.
|
||||
ES6 提供了一个新的创建对象的语法,使用关键字 <dfn>class</dfn>。
|
||||
|
||||
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');
|
||||
|
@ -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));
|
||||
|
@ -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);
|
||||
|
@ -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);
|
||||
|
@ -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--
|
||||
|
||||
<dfn>Destructuring assignment</dfn> is special syntax introduced in ES6, for neatly assigning values taken directly from an object.
|
||||
<dfn>解构赋值</dfn>是 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);
|
||||
|
@ -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/));
|
||||
|
@ -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(
|
||||
|
@ -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(
|
||||
|
@ -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 <dfn>getters</dfn> and <dfn>setters</dfn>.
|
||||
这些操作通常被称为 <dfn>getters</dfn> 以及 <dfn>setters</dfn>。
|
||||
|
||||
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(
|
||||
|
@ -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 <dfn>rest parameter</dfn> 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 推出了用于函数参数的 <dfn>rest 操作符</dfn>帮助我们创建更加灵活的函数。 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\)=>/));
|
||||
|
@ -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 <dfn>spread operator</dfn>, which allows us to expand arrays and other expressions in places where multiple parameters or elements are expected.
|
||||
ES6 引入了<dfn>展开操作符</dfn>,可以展开数组以及需要多个参数或元素的表达式。
|
||||
|
||||
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) => {
|
||||
|
@ -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));
|
||||
|
@ -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);
|
||||
|
@ -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));
|
||||
|
Reference in New Issue
Block a user