chore(i8n,learn): processed translations
This commit is contained in:
committed by
Mrugesh Mohapatra
parent
15047f2d90
commit
e5c44a3ae5
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a661e0f1068aca922b3ef17
|
||||
title: 使用方括号访问数组的元素
|
||||
title: Access an Array's Contents Using Bracket Notation
|
||||
challengeType: 1
|
||||
forumTopicId: 301149
|
||||
dashedName: access-an-arrays-contents-using-bracket-notation
|
||||
@ -8,55 +8,55 @@ dashedName: access-an-arrays-contents-using-bracket-notation
|
||||
|
||||
# --description--
|
||||
|
||||
所有数据结构的基本特性是,它们不仅可以存储数据,还可以让我们按需访问存放在其中的数据。我们已经学习了如何创建数组,现在让我们来学习如何访问数组中的数据。
|
||||
The fundamental feature of any data structure is, of course, the ability to not only store data, but to be able to retrieve that data on command. So, now that we've learned how to create an array, let's begin to think about how we can access that array's information.
|
||||
|
||||
我们先定义一个包含 3 个元素的数组:
|
||||
When we define a simple array as seen below, there are 3 items in it:
|
||||
|
||||
```js
|
||||
let ourArray = ["a", "b", "c"];
|
||||
```
|
||||
|
||||
在数组中,内部的每个元素都有一个与之对应的<dfn>索引</dfn>(<dfn>index</dfn>)。索引既是该元素在数组中的位置,也是我们访问该元素的参考。需要注意的是,JavaScript 数组的索引是从 0 开始的(这种从 0 开始的规则叫做 <dfn>zero-indexed</dfn>),即数组的第一个元素是在数组中的***第 0 个***位置,而不是第 1 个位置。要从数组中获取一个元素,我们可以在数组字面量后面加一个用方括号(`[]`)括起来的索引。不过习惯上,我们会通过表示数组的变量名来访问,而不是直接通过字面量。这种从数组中读取元素的方式叫做<dfn>方括号表示法</dfn>(<dfn>bracket notation</dfn>)。如果我们要从数组 `ourArray` 中获取数据元素 `"a"` 并将其赋值给另一个变量,可以这样写:
|
||||
In an array, each array item has an <dfn>index</dfn>. This index doubles as the position of that item in the array, and how you reference it. However, it is important to note, that JavaScript arrays are <dfn>zero-indexed</dfn>, meaning that the first element of an array is actually at the ***zeroth*** position, not the first. In order to retrieve an element from an array we can enclose an index in brackets and append it to the end of an array, or more commonly, to a variable which references an array object. This is known as <dfn>bracket notation</dfn>. For example, if we want to retrieve the `"a"` from `ourArray` and assign it to a variable, we can do so with the following code:
|
||||
|
||||
```js
|
||||
let ourVariable = ourArray[0];
|
||||
// ourVariable 的值为 "a"
|
||||
// ourVariable equals "a"
|
||||
```
|
||||
|
||||
除了使用索引来获取某个元素值以外,你还可以通过类似的写法来*设置*一个索引位置的元素值:
|
||||
In addition to accessing the value associated with an index, you can also *set* an index to a value using the same notation:
|
||||
|
||||
```js
|
||||
ourArray[1] = "not b anymore";
|
||||
// ourArray 现在的值为 ["a", "not b anymore", "c"];
|
||||
// ourArray now equals ["a", "not b anymore", "c"];
|
||||
```
|
||||
|
||||
在上面的代码中,我们用方括号表示法把索引为 1 的元素从 `"b"` 改成了 `"not b anymore"`。
|
||||
Using bracket notation, we have now reset the item at index 1 from `"b"`, to `"not b anymore"`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
在本挑战中,请将 `myArray` 中的第二个元素(索引为 `1`)设置为除了 `"b"` 以外的任意值。
|
||||
In order to complete this challenge, set the 2nd position (index `1`) of `myArray` to anything you want, besides `"b"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray[0]` 应为 `"a"`。
|
||||
`myArray[0]` should be equal to `"a"`
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[0], 'a');
|
||||
```
|
||||
|
||||
`myArray[1]` 不应为 `"b"`。
|
||||
`myArray[1]` should not be equal to `"b"`
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(myArray[1], 'b');
|
||||
```
|
||||
|
||||
`myArray[2]` 应为 `"c"`。
|
||||
`myArray[2]` should be equal to `"c"`
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[2], 'c');
|
||||
```
|
||||
|
||||
`myArray[3]` 应为 `"d"`。
|
||||
`myArray[3]` should be equal to `"d"`
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[3], 'd');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b1a
|
||||
title: 使用方括号访问属性名称
|
||||
title: Access Property Names with Bracket Notation
|
||||
challengeType: 1
|
||||
forumTopicId: 301150
|
||||
dashedName: access-property-names-with-bracket-notation
|
||||
@ -8,28 +8,28 @@ dashedName: access-property-names-with-bracket-notation
|
||||
|
||||
# --description--
|
||||
|
||||
在关于对象的第一个挑战中,我们提到可以在一对方括号中用一个变量作为属性名来访问属性的值。假设一个超市收银台程序中有一个 `foods` 对象,并且有一个函数会设置 `selectedFood`;如果我们需要查询 `foods` 对象中,某种食物是否存在,可以这样实现:
|
||||
In the first object challenge we mentioned the use of bracket notation as a way to access property values using the evaluation of a variable. For instance, imagine that our `foods` object is being used in a program for a supermarket cash register. We have some function that sets the `selectedFood` and we want to check our `foods` object for the presence of that food. This might look like:
|
||||
|
||||
```js
|
||||
let selectedFood = getCurrentFood(scannedItem);
|
||||
let inventory = foods[selectedFood];
|
||||
```
|
||||
|
||||
上述代码会先读取 `selectedFood` 变量的值,并返回 `foods` 对象中以该值命名的属性所对应的属性值。若没有以该值命名的属性,则会返回 `undefined`。有时候对象的属性名在运行之前是不确定的,或者我们需要动态地访问对象的属性值。在这些场景下,方括号表示法就变得十分有用。
|
||||
This code will evaluate the value stored in the `selectedFood` variable and return the value of that key in the `foods` object, or `undefined` if it is not present. Bracket notation is very useful because sometimes object properties are not known before runtime or we need to access them in a more dynamic way.
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了 `checkInventory` 函数,它接受一个被扫描到的商品名作为输入参数。请让这个函数返回 `foods` 对象中,以 `scannedItem` 的值所命名的属性对应的属性值。在本挑战中,只有合理有效的属性名会作为参数传入 `checkInventory`,因此你不需要处理参数无效的情况。
|
||||
We've defined a function, `checkInventory`, which receives a scanned item as an argument. Return the current value of the `scannedItem` key in the `foods` object. You can assume that only valid keys will be provided as an argument to `checkInventory`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`checkInventory` 应是一个函数。
|
||||
`checkInventory` should be a function.
|
||||
|
||||
```js
|
||||
assert.strictEqual(typeof checkInventory, 'function');
|
||||
```
|
||||
|
||||
`foods` 对象应只包含以下键值对:`apples: 25`、`oranges: 32`、`plums: 28`、`bananas: 13`、`grapes: 35`、`strawberries: 27`。
|
||||
The `foods` object should have only the following key-value pairs: `apples: 25`, `oranges: 32`, `plums: 28`, `bananas: 13`, `grapes: 35`, `strawberries: 27`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(foods, {
|
||||
@ -42,19 +42,19 @@ assert.deepEqual(foods, {
|
||||
});
|
||||
```
|
||||
|
||||
`checkInventory("apples")` 应返回 `25`。
|
||||
`checkInventory("apples")` should return `25`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(checkInventory('apples'), 25);
|
||||
```
|
||||
|
||||
`checkInventory("bananas")` 应返回 `13`。
|
||||
`checkInventory("bananas")` should return `13`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(checkInventory('bananas'), 13);
|
||||
```
|
||||
|
||||
`checkInventory("strawberries")` 应返回 `27`。
|
||||
`checkInventory("strawberries")` should return `27`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(checkInventory('strawberries'), 27);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b0e
|
||||
title: 使用 push() 和 unshift() 为数组添加元素
|
||||
title: Add Items to an Array with push() and unshift()
|
||||
challengeType: 1
|
||||
forumTopicId: 301151
|
||||
dashedName: add-items-to-an-array-with-push-and-unshift
|
||||
@ -8,30 +8,28 @@ dashedName: add-items-to-an-array-with-push-and-unshift
|
||||
|
||||
# --description--
|
||||
|
||||
数组的长度与数组能包含的数据类型一样,都是不固定的。数组可以包含任意数量的元素,可以不限次数地往数组中添加元素或者从中移除元素。总之,数组是<dfn>可变的</dfn>(<dfn>mutable</dfn>)。在本挑战中,我们要学习两种修改数组的方法:`Array.push()` 和 `Array.unshift()`。
|
||||
An array's length, like the data types it can contain, is not fixed. Arrays can be defined with a length of any number of elements, and elements can be added or removed over time; in other words, arrays are <dfn>mutable</dfn>. In this challenge, we will look at two methods with which we can programmatically modify an array: `Array.push()` and `Array.unshift()`.
|
||||
|
||||
这两个方法都接收一个或多个元素作为参数,并会将参数中的元素添加到该数组中。`push()` 方法会将元素插入到数组的末尾,而 `unshift()` 方法会将元素插入到数组的开头。请看以下例子:
|
||||
Both methods take one or more elements as parameters and add those elements to the array the method is being called on; the `push()` method adds elements to the end of an array, and `unshift()` adds elements to the beginning. Consider the following:
|
||||
|
||||
```js
|
||||
let twentyThree = 'XXIII';
|
||||
let romanNumerals = ['XXI', 'XXII'];
|
||||
|
||||
romanNumerals.unshift('XIX', 'XX');
|
||||
// 数组现在为 ['XIX', 'XX', 'XXI', 'XXII']
|
||||
// now equals ['XIX', 'XX', 'XXI', 'XXII']
|
||||
|
||||
romanNumerals.push(twentyThree);
|
||||
// 数组现在为 ['XIX', 'XX', 'XXI', 'XXII', 'XXIII']
|
||||
// now equals ['XIX', 'XX', 'XXI', 'XXII', 'XXIII']Notice that we can also pass variables, which allows us even greater flexibility in dynamically modifying our array's data.
|
||||
```
|
||||
|
||||
**注意:**我们甚至可以传入变量,这在动态改变数组数据的场景下十分有用。
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个 `mixedNumbers` 函数,它接收一个数组作为参数。请你修改这个函数,使用 `push()` 和 `unshift()` 来将 `'I', 2, 'three'` 插入到数组开头,将 `7, 'VIII', 9` 插入到数组的末尾,使得这个函数返回一个依次包含 1 至 9。
|
||||
We have defined a function, `mixedNumbers`, which we are passing an array as an argument. Modify the function by using `push()` and `unshift()` to add `'I', 2, 'three'` to the beginning of the array and `7, 'VIII', 9` to the end so that the returned array contains representations of the numbers 1-9 in order.
|
||||
|
||||
# --hints--
|
||||
|
||||
`mixedNumbers(["IV", 5, "six"])` 应返回 `["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]`。
|
||||
`mixedNumbers(["IV", 5, "six"])` should now return `["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(mixedNumbers(['IV', 5, 'six']), [
|
||||
@ -47,13 +45,13 @@ assert.deepEqual(mixedNumbers(['IV', 5, 'six']), [
|
||||
]);
|
||||
```
|
||||
|
||||
`mixedNumbers` 函数中应调用 `push()` 方法。
|
||||
The `mixedNumbers` function should utilize the `push()` method
|
||||
|
||||
```js
|
||||
assert(mixedNumbers.toString().match(/\.push/));
|
||||
```
|
||||
|
||||
`mixedNumbers` 函数中应调用 `unshift()` 方法。
|
||||
The `mixedNumbers` function should utilize the `unshift()` method
|
||||
|
||||
```js
|
||||
assert(mixedNumbers.toString().match(/\.unshift/));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d78b3367417b2b2512b11
|
||||
title: 使用 splice() 添加元素
|
||||
title: Add Items Using splice()
|
||||
challengeType: 1
|
||||
forumTopicId: 301152
|
||||
dashedName: add-items-using-splice
|
||||
@ -8,7 +8,7 @@ dashedName: add-items-using-splice
|
||||
|
||||
# --description--
|
||||
|
||||
还记得在上个挑战中我们提到 `splice()` 方法最多可以接收 3 个参数吗?除了移除元素,我们还可以利用它的第三个参数来向数组中*添加*元素。第三个参数可以是一个或多个元素,这些元素会被添加到数组中。这样,我们能够便捷地将数组中的一个或多个连续元素换成其他的元素。例如:
|
||||
Remember in the last challenge we mentioned that `splice()` can take up to three parameters? Well, you can use the third parameter, comprised of one or more element(s), to add to the array. This can be incredibly useful for quickly switching out an element, or a set of elements, for another.
|
||||
|
||||
```js
|
||||
const numbers = [10, 11, 12, 12, 15];
|
||||
@ -16,20 +16,20 @@ const startIndex = 3;
|
||||
const amountToDelete = 1;
|
||||
|
||||
numbers.splice(startIndex, amountToDelete, 13, 14);
|
||||
// 第二个 12 被移除,在第二个 12 的索引处添加 13、14。
|
||||
// the second entry of 12 is removed, and we add 13 and 14 at the same index
|
||||
console.log(numbers);
|
||||
// 返回 [ 10, 11, 12, 13, 14, 15 ]
|
||||
// returns [ 10, 11, 12, 13, 14, 15 ]
|
||||
```
|
||||
|
||||
在上面的代码中,数组一开始包含了若干数字。接着,我们调用 `splice()` 方法,索引为 (3) 的地方开始删除元素,删除的元素数量是 (1)。然后,(13, 14) 是在删除位置插入的元素,可以在 `amountToDelete` 后面传入任意数量的元素(以逗号分隔),每个都会被插入到数组中。
|
||||
Here, we begin with an array of numbers. Then, we pass the following to `splice()`: The index at which to begin deleting elements (3), the number of elements to be deleted (1), and the remaining arguments (13, 14) will be inserted starting at that same index. Note that there can be any number of elements (separated by commas) following `amountToDelete`, each of which gets inserted.
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个 `htmlColorNames` 函数,它以一个 HTML 颜色的数组作为输入参数。请修改这个函数,使用 `splice()` 来移除数组中的前两个元素,并在对应的位置上添加 `'DarkSalmon'` 和 `'BlanchedAlmond'`。
|
||||
We have defined a function, `htmlColorNames`, which takes an array of HTML colors as an argument. Modify the function using `splice()` to remove the first two elements of the array and add `'DarkSalmon'` and `'BlanchedAlmond'` in their respective places.
|
||||
|
||||
# --hints--
|
||||
|
||||
`htmlColorNames` 应返回 `["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurqoise", "FireBrick"]`。
|
||||
`htmlColorNames` should return `["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurquoise", "FireBrick"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -50,19 +50,19 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`htmlColorNames` 函数中应调用 `splice()` 方法。
|
||||
The `htmlColorNames` function should utilize the `splice()` method
|
||||
|
||||
```js
|
||||
assert(/.splice/.test(code));
|
||||
```
|
||||
|
||||
不应使用 `shift()` 或 `unshift()`。
|
||||
You should not use `shift()` or `unshift()`.
|
||||
|
||||
```js
|
||||
assert(!/shift|unshift/.test(code));
|
||||
```
|
||||
|
||||
不应使用数组的方括号表示法。
|
||||
You should not use array bracket notation.
|
||||
|
||||
```js
|
||||
assert(!/\[\d\]\s*=/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b18
|
||||
title: 将键值对添加到对象中
|
||||
title: Add Key-Value Pairs to JavaScript Objects
|
||||
challengeType: 1
|
||||
forumTopicId: 301153
|
||||
dashedName: add-key-value-pairs-to-javascript-objects
|
||||
@ -8,7 +8,7 @@ dashedName: add-key-value-pairs-to-javascript-objects
|
||||
|
||||
# --description--
|
||||
|
||||
对象(object)本质上是<dfn>键值对(key-value pair)</dfn>的集合。或者说,一系列被映射到唯一标识符的数据就是对象;习惯上,唯一标识符叫做<dfn>属性(property)</dfn>或者<dfn>键(key)</dfn>);数据叫做<dfn>值(value)</dfn>。让我们来看一个简单的例子:
|
||||
At their most basic, objects are just collections of <dfn>key-value</dfn> pairs. In other words, they are pieces of data (<dfn>values</dfn>) mapped to unique identifiers called <dfn>properties</dfn> (<dfn>keys</dfn>). Take a look at an example:
|
||||
|
||||
```js
|
||||
const tekkenCharacter = {
|
||||
@ -18,19 +18,19 @@ const tekkenCharacter = {
|
||||
};
|
||||
```
|
||||
|
||||
上面的代码定义了一个叫做 `tekkenCharacter` 的“铁拳”游戏人物对象。它有三个属性,每个属性都对应一个特定的值。如果我们想为它再添加一个叫做 `origin` 的属性,可以这样写:
|
||||
The above code defines a Tekken video game character object called `tekkenCharacter`. It has three properties, each of which map to a specific value. If you want to add an additional property, such as "origin", it can be done by assigning `origin` to the object:
|
||||
|
||||
```js
|
||||
tekkenCharacter.origin = 'South Korea';
|
||||
```
|
||||
|
||||
上面的代码中,我们使用了<dfn>点号表示法(dot notation)</dfn>。如果我们现在输出这个对象,便可以看到它具有 `origin` 属性。接下来,因为这个人物在游戏中有着与众不同的橘色头发,我们可以通过方括号表示法来为它添加这个属性,像这样:
|
||||
This uses dot notation. If you were to observe the `tekkenCharacter` object, it will now include the `origin` property. Hwoarang also had distinct orange hair. You can add this property with bracket notation by doing:
|
||||
|
||||
```js
|
||||
tekkenCharacter['hair color'] = 'dyed orange';
|
||||
```
|
||||
|
||||
如果要设置的属性中存在空格,或者要设置的属性是一个变量,那我们必须使用<dfn>方括号表示法(bracket notation)</dfn>来为对象添加属性。在上面的代码中,我们把属性 `hair color` 放到引号里,以此来表示整个字符串都是需要设置的属性。如果我们不加上引号,那么中括号里的内容会被当作一个变量来解析,这个变量对应的值就会作为要设置的属性,请看这段代码:
|
||||
Bracket notation is required if your property has a space in it or if you want to use a variable to name the property. In the above case, the property is enclosed in quotes to denote it as a string and will be added exactly as shown. Without quotes, it will be evaluated as a variable and the name of the property will be whatever value the variable is. Here's an example with a variable:
|
||||
|
||||
```js
|
||||
const eyes = 'eye color';
|
||||
@ -38,7 +38,7 @@ const eyes = 'eye color';
|
||||
tekkenCharacter[eyes] = 'brown';
|
||||
```
|
||||
|
||||
执行以上所有示例代码后,对象会变成这样:
|
||||
After adding all the examples, the object will look like this:
|
||||
|
||||
```js
|
||||
{
|
||||
@ -53,35 +53,35 @@ tekkenCharacter[eyes] = 'brown';
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经为你创建了 `foods` 对象。请使用上述任意语法,来为 `foods` 对象添加如下三个键值对:`bananas` 属性,值为 `13`;`grapes` 属性,值为 `35`;`strawberries` 属性,值为 `27`。
|
||||
A `foods` object has been created with three entries. Using the syntax of your choice, add three more entries to it: `bananas` with a value of `13`, `grapes` with a value of `35`, and `strawberries` with a value of `27`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`foods` 应为一个对象。
|
||||
`foods` should be an object.
|
||||
|
||||
```js
|
||||
assert(typeof foods === 'object');
|
||||
```
|
||||
|
||||
`foods` 应有一个值为 `13` 的 `"bananas"` 属性。
|
||||
The `foods` object should have a key `"bananas"` with a value of `13`.
|
||||
|
||||
```js
|
||||
assert(foods.bananas === 13);
|
||||
```
|
||||
|
||||
`foods` 应有一个值为 `35` 的 `"grapes"` 属性。
|
||||
The `foods` object should have a key `"grapes"` with a value of `35`.
|
||||
|
||||
```js
|
||||
assert(foods.grapes === 35);
|
||||
```
|
||||
|
||||
`foods` 应有一个值为 `27` 的 `"strawberries"` 属性。
|
||||
The `foods` object should have a key `"strawberries"` with a value of `27`.
|
||||
|
||||
```js
|
||||
assert(foods.strawberries === 27);
|
||||
```
|
||||
|
||||
应使用点号表示法或方括号表示法来设置对象的属性。
|
||||
The key-value pairs should be set using dot or bracket notation.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b14
|
||||
title: 使用 indexOf() 检查元素是否存在
|
||||
title: Check For The Presence of an Element With indexOf()
|
||||
challengeType: 1
|
||||
forumTopicId: 301154
|
||||
dashedName: check-for-the-presence-of-an-element-with-indexof
|
||||
@ -8,25 +8,31 @@ dashedName: check-for-the-presence-of-an-element-with-indexof
|
||||
|
||||
# --description--
|
||||
|
||||
由于数组随时都可以修改或发生“突变”(*mutated*),我们很难保证某个数据始终处于数组中的特定位置,甚至不能保证该元素是否还存在于该数组中。好消息是,JavaScript 为我们提供了内置方法 `indexOf()`。这个方法让我们可以方便地检查某个元素是否存在于数组中。`indexOf()` 方法接受一个元素作为输入参数,并返回该元素在数组中的位置(索引);若该元素不存在于数组中则返回 `-1`。
|
||||
Since arrays can be changed, or *mutated*, at any time, there's no guarantee about where a particular piece of data will be on a given array, or if that element even still exists. Luckily, JavaScript provides us with another built-in method, `indexOf()`, that allows us to quickly and easily check for the presence of an element on an array. `indexOf()` takes an element as a parameter, and when called, it returns the position, or index, of that element, or `-1` if the element does not exist on the array.
|
||||
|
||||
例如:
|
||||
For example:
|
||||
|
||||
```js
|
||||
let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];
|
||||
|
||||
fruits.indexOf('dates'); // 返回 -1
|
||||
fruits.indexOf('oranges'); // 返回 2
|
||||
fruits.indexOf('pears'); // 返回 1,因为第一个出现在数组中的 'pears' 元素索引为 1
|
||||
fruits.indexOf('dates'); // returns -1
|
||||
fruits.indexOf('oranges'); // returns 2
|
||||
fruits.indexOf('pears'); // returns 1, the first index at which the element exists
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
`indexOf()` 在快速检查一个数组中是否存在某个元素时非常有用。我们已经定义了一个 `quickCheck` 函数,它接受一个数组和一个元素作为输入参数。请修改这个函数,通过 `indexOf()` 方法,使得当参数数组中包含第二个参数的元素时返回 `true`,不包含时返回 `false`。
|
||||
`indexOf()` can be incredibly useful for quickly checking for the presence of an element on an array. We have defined a function, `quickCheck`, that takes an array and an element as arguments. Modify the function using `indexOf()` so that it returns `true` if the passed element exists on the array, and `false` if it does not.
|
||||
|
||||
# --hints--
|
||||
|
||||
`quickCheck(["squash", "onions", "shallots"], "mushrooms")` 应返回 `false`。
|
||||
The `quickCheck` function should return a boolean (`true` or `false`), not a string (`"true"` or `"false"`)
|
||||
|
||||
```js
|
||||
assert.isBoolean(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
|
||||
```
|
||||
|
||||
`quickCheck(["squash", "onions", "shallots"], "mushrooms")` should return `false`
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -35,7 +41,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`quickCheck(["squash", "onions", "shallots"], "onions")` 应返回 `true`。
|
||||
`quickCheck(["onions", "squash", "shallots"], "onions")` should return `true`
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -44,19 +50,19 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`quickCheck([3, 5, 9, 125, 45, 2], 125)` 应返回 `true`。
|
||||
`quickCheck([3, 5, 9, 125, 45, 2], 125)` should return `true`
|
||||
|
||||
```js
|
||||
assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true);
|
||||
```
|
||||
|
||||
`quickCheck([true, false, false], undefined)` 应返回 `false`。
|
||||
`quickCheck([true, false, false], undefined)` should return `false`
|
||||
|
||||
```js
|
||||
assert.strictEqual(quickCheck([true, false, false], undefined), false);
|
||||
```
|
||||
|
||||
`quickCheck` 函数中应使用 `indexOf()` 方法。
|
||||
The `quickCheck` function should utilize the `indexOf()` method
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1c
|
||||
title: 检查对象是否具有某个属性
|
||||
title: Check if an Object has a Property
|
||||
challengeType: 1
|
||||
forumTopicId: 301155
|
||||
dashedName: check-if-an-object-has-a-property
|
||||
@ -8,21 +8,21 @@ dashedName: check-if-an-object-has-a-property
|
||||
|
||||
# --description--
|
||||
|
||||
我们已经学习了如果添加、修改和移除对象中的属性。但如果我们想知道一个对象中是否包含某个属性呢?JavaScript 为我们提供了两种不同的方式来实现这个功能:一个是通过 `hasOwnProperty()` 方法,另一个是使用 `in` 关键字。假如我们有一个 `users` 对象,为检查它是否含有 `Alan` 属性,可以这样写:
|
||||
Now we can add, modify, and remove keys from objects. But what if we just wanted to know if an object has a specific property? JavaScript provides us with two different ways to do this. One uses the `hasOwnProperty()` method and the other uses the `in` keyword. If we have an object `users` with a property of `Alan`, we could check for its presence in either of the following ways:
|
||||
|
||||
```js
|
||||
users.hasOwnProperty('Alan');
|
||||
'Alan' in users;
|
||||
// 都返回 true
|
||||
// both return true
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个包含若干用户信息的 `users` 对象和一个 `isEveryoneHere` 函数,该函数接收 `users` 对象作为参数。请完成该函数使其在 `users` 对象中同时包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 四个属性时才返回 `true`,否则返回 `false`。
|
||||
We've created an object, `users`, with some users in it and a function `isEveryoneHere`, which we pass the `users` object to as an argument. Finish writing this function so that it returns `true` only if the `users` object contains all four names, `Alan`, `Jeff`, `Sarah`, and `Ryan`, as keys, and `false` otherwise.
|
||||
|
||||
# --hints--
|
||||
|
||||
`users` 对象应该只包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 4 个属性。
|
||||
The `users` object should only contain the keys `Alan`, `Jeff`, `Sarah`, and `Ryan`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -34,13 +34,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`isEveryoneHere` 函数在 `users` 对象包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 4 个属性时应返回 `true`。
|
||||
The function `isEveryoneHere` should return `true` if `Alan`, `Jeff`, `Sarah`, and `Ryan` are properties on the `users` object
|
||||
|
||||
```js
|
||||
assert(isEveryoneHere(users) === true);
|
||||
```
|
||||
|
||||
`isEveryoneHere` 函数在 `users` 对象不包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 4 个属性时应返回 `false`。
|
||||
The function `isEveryoneHere` should return `false` if `Alan` is not a property on the `users` object
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -51,7 +51,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
如果 `users` 对象中不包含属性 `Jeff`,则函数 `isEveryoneHere` 应返回 `false`。
|
||||
The function `isEveryoneHere` should return `false` if `Jeff` is not a property on the `users` object
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -62,7 +62,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
如果 `users` 对象中不包含属性 `Sarah`,则函数 `isEveryoneHere` 应返回 `false`。
|
||||
The function `isEveryoneHere` should return `false` if `Sarah` is not a property on the `users` object
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -73,7 +73,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
如果 `users` 对象中不包含属性 `Ryan`,则函数 `isEveryoneHere` 应返回 `false`。
|
||||
The function `isEveryoneHere` should return `false` if `Ryan` is not a property on the `users` object
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b17
|
||||
title: 使用展开运算符合并数组
|
||||
title: Combine Arrays with the Spread Operator
|
||||
challengeType: 1
|
||||
forumTopicId: 301156
|
||||
dashedName: combine-arrays-with-the-spread-operator
|
||||
@ -8,30 +8,30 @@ dashedName: combine-arrays-with-the-spread-operator
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>展开语法</dfn>的另一个重要用途是合并数组,或者将某个数组的所有元素插入到另一个数组的任意位置。我们也可以使用 ES5 的语法连接两个数组,但只能让它们首尾相接。而展开语法可以让这样的操作变得极其简单:
|
||||
Another huge advantage of the <dfn>spread</dfn> operator, is the ability to combine arrays, or to insert all the elements of one array into another, at any index. With more traditional syntaxes, we can concatenate arrays, but this only allows us to combine arrays at the end of one, and at the start of another. Spread syntax makes the following operation extremely simple:
|
||||
|
||||
```js
|
||||
let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];
|
||||
|
||||
let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander'];
|
||||
// thatArray 现在是 ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']
|
||||
// thatArray now equals ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']
|
||||
```
|
||||
|
||||
使用展开语法,我们像这样就可以实现一个用传统方法会写得很复杂且冗长的操作。
|
||||
Using spread syntax, we have just achieved an operation that would have been more complex and more verbose had we used traditional methods.
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个返回 `sentence` 变量的 `spreadOut` 函数。请修改这个函数,利用<dfn>展开语法</dfn>使该函数返回数组 `['learning', 'to', 'code', 'is', 'fun']`。
|
||||
We have defined a function `spreadOut` that returns the variable `sentence`. Modify the function using the <dfn>spread</dfn> operator so that it returns the array `['learning', 'to', 'code', 'is', 'fun']`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`spreadOut` 应返回 `["learning", "to", "code", "is", "fun"]`。
|
||||
`spreadOut` should return `["learning", "to", "code", "is", "fun"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(spreadOut(), ['learning', 'to', 'code', 'is', 'fun']);
|
||||
```
|
||||
|
||||
`spreadOut` 函数里应用到展开语法。
|
||||
The `spreadOut` function should utilize spread syntax
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(spreadOut.toString().search(/[...]/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b13
|
||||
title: 使用展开运算符复制数组
|
||||
title: Copy an Array with the Spread Operator
|
||||
challengeType: 1
|
||||
forumTopicId: 301157
|
||||
dashedName: copy-an-array-with-the-spread-operator
|
||||
@ -8,24 +8,24 @@ dashedName: copy-an-array-with-the-spread-operator
|
||||
|
||||
# --description--
|
||||
|
||||
`slice()` 可以让我们从一个数组中选择一些元素来复制到新数组中,而 ES6 中又引入了一个简洁且可读性强的语法:<dfn>展开运算符(spread operator)</dfn>,它能让我们方便地复制数组中的*所有*元素。展开语法写出来是这样:`...`
|
||||
While `slice()` allows us to be selective about what elements of an array to copy, among several other useful tasks, ES6's new <dfn>spread operator</dfn> allows us to easily copy *all* of an array's elements, in order, with a simple and highly readable syntax. The spread syntax simply looks like this: `...`
|
||||
|
||||
我们可以用展开运算符来复制数组:
|
||||
In practice, we can use the spread operator to copy an array like so:
|
||||
|
||||
```js
|
||||
let thisArray = [true, true, undefined, false, null];
|
||||
let thatArray = [...thisArray];
|
||||
// thatArray 的值现在也是 [true, true, undefined, false, null]
|
||||
// thisArray 保持不变。现在 thatArray 所包含的值与 thisArray 完全相同
|
||||
// thatArray equals [true, true, undefined, false, null]
|
||||
// thisArray remains unchanged and thatArray contains the same elements as thisArray
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个 `copyMachine` 函数,它接受 `arr`(一个数组)和 `num`(一个数字)作为输入参数。该函数需要返回一个由 `num` 个 `arr` 组成的新的二维数组。同时,我们写好了大致的流程,只是细节实现还没有写完。请修改这个函数,使用展开语法,使该函数能正常工作(提示:我们已经学到过的一个方法很适合用在这里)!
|
||||
We have defined a function, `copyMachine` which takes `arr` (an array) and `num` (a number) as arguments. The function is supposed to return a new array made up of `num` copies of `arr`. We have done most of the work for you, but it doesn't work quite right yet. Modify the function using spread syntax so that it works correctly (hint: another method we have already covered might come in handy here!).
|
||||
|
||||
# --hints--
|
||||
|
||||
`copyMachine([true, false, true], 2)` 应返回 `[[true, false, true], [true, false, true]]`。
|
||||
`copyMachine([true, false, true], 2)` should return `[[true, false, true], [true, false, true]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([true, false, true], 2), [
|
||||
@ -34,7 +34,7 @@ assert.deepEqual(copyMachine([true, false, true], 2), [
|
||||
]);
|
||||
```
|
||||
|
||||
`copyMachine([1, 2, 3], 5)` 应返回 `[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]`。
|
||||
`copyMachine([1, 2, 3], 5)` should return `[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([1, 2, 3], 5), [
|
||||
@ -46,13 +46,13 @@ assert.deepEqual(copyMachine([1, 2, 3], 5), [
|
||||
]);
|
||||
```
|
||||
|
||||
`copyMachine([true, true, null], 1)` 应返回 `[[true, true, null]]`。
|
||||
`copyMachine([true, true, null], 1)` should return `[[true, true, null]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]]);
|
||||
```
|
||||
|
||||
`copyMachine(["it works"], 3)` 应返回 `[["it works"], ["it works"], ["it works"]]`。
|
||||
`copyMachine(["it works"], 3)` should return `[["it works"], ["it works"], ["it works"]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine(['it works'], 3), [
|
||||
@ -62,10 +62,10 @@ assert.deepEqual(copyMachine(['it works'], 3), [
|
||||
]);
|
||||
```
|
||||
|
||||
`copyMachine` 函数中应对 `arr` 使用`展开运算符`。
|
||||
The `copyMachine` function should utilize the `spread operator` with array `arr`
|
||||
|
||||
```js
|
||||
assert(removeJSComments(code).match(/\.\.\.arr/));
|
||||
assert(__helpers.removeJSComments(code).match(/\.\.\.arr/));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7a367417b2b2512b12
|
||||
title: 使用 slice() 复制数组元素
|
||||
title: Copy Array Items Using slice()
|
||||
challengeType: 1
|
||||
forumTopicId: 301158
|
||||
dashedName: copy-array-items-using-slice
|
||||
@ -8,25 +8,25 @@ dashedName: copy-array-items-using-slice
|
||||
|
||||
# --description--
|
||||
|
||||
接下来我们要介绍 `slice()` 方法。`slice()` 不会修改数组,而是会复制,或者说*提取(extract)*给定数量的元素到一个新数组。同时,调用方法的数组保持不变。`slice()` 只接收 2 个输入参数:第一个是开始提取元素的位置(索引),第二个是提取元素的结束位置(索引)。`slice()` 提取的元素中不包括第二个参数所对应的元素。请看以下例子:
|
||||
The next method we will cover is `slice()`. Rather than modifying an array, `slice()` copies or *extracts* a given number of elements to a new array, leaving the array it is called upon untouched. `slice()` takes only 2 parameters — the first is the index at which to begin extraction, and the second is the index at which to stop extraction (extraction will occur up to, but not including the element at this index). Consider this:
|
||||
|
||||
```js
|
||||
let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
|
||||
|
||||
let todaysWeather = weatherConditions.slice(1, 3);
|
||||
// todaysWeather 等于 ['snow', 'sleet'];
|
||||
// weatherConditions 仍然等于 ['rain', 'snow', 'sleet', 'hail', 'clear']
|
||||
// todaysWeather equals ['snow', 'sleet'];
|
||||
// weatherConditions still equals ['rain', 'snow', 'sleet', 'hail', 'clear']
|
||||
```
|
||||
|
||||
在上面的代码中,我们从一个数组中提取了一些元素,并用这些元素创建了一个新数组。
|
||||
In effect, we have created a new array by extracting elements from an existing array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个 `forecast` 函数,它接受一个数组作为参数。请修改这个函数,利用 `slice()` 从输入的数组中提取信息,最终返回一个包含元素 `'warm'` 和 `'sunny'` 的新数组。
|
||||
We have defined a function, `forecast`, that takes an array as an argument. Modify the function using `slice()` to extract information from the argument array and return a new array that contains the elements `'warm'` and `'sunny'`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`forecast` 应返回 `["warm", "sunny"]`。
|
||||
`forecast` should return `["warm", "sunny"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -35,7 +35,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`forecast` 函数中应使用 `slice()` 方法。
|
||||
The `forecast` function should utilize the `slice()` method
|
||||
|
||||
```js
|
||||
assert(/\.slice\(/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b16
|
||||
title: 创建复杂的多维数组
|
||||
title: Create complex multi-dimensional arrays
|
||||
challengeType: 1
|
||||
forumTopicId: 301159
|
||||
dashedName: create-complex-multi-dimensional-arrays
|
||||
@ -8,37 +8,37 @@ dashedName: create-complex-multi-dimensional-arrays
|
||||
|
||||
# --description--
|
||||
|
||||
很好!你现在已经学到很多关于数组的知识了,但这些只是个开始。我们将在接下来的中挑战中学到更多与数组相关的知识。在继续学习<dfn>对象</dfn>(<dfn>Objects</dfn>)之前,让我们再花一点时间了解下更复杂的数组嵌套。
|
||||
Awesome! You have just learned a ton about arrays! This has been a fairly high level overview, and there is plenty more to learn about working with arrays, much of which you will see in later sections. But before moving on to looking at <dfn>Objects</dfn>, lets take one more look, and see how arrays can become a bit more complex than what we have seen in previous challenges.
|
||||
|
||||
数组的一个强大的特性是,它可以包含其他数组,甚至完全由其他数组组成。在上一个挑战中,我们已经接触到了包含数组的数组,但它还算是比较简单的。数组中的数组还可以再包含其他数组,即可以嵌套任意多层数组。习惯上,我们称这种数据结构为<dfn>多维(multi-dimensional)数组</dfn>或嵌套(nested)数组。请看如下的示例:
|
||||
One of the most powerful features when thinking of arrays as data structures, is that arrays can contain, or even be completely made up of other arrays. We have seen arrays that contain arrays in previous challenges, but fairly simple ones. However, arrays can contain an infinite depth of arrays that can contain other arrays, each with their own arbitrary levels of depth, and so on. In this way, an array can very quickly become very complex data structure, known as a <dfn>multi-dimensional</dfn>, or nested array. Consider the following example:
|
||||
|
||||
```js
|
||||
let nestedArray = [ // 顶层,或第 1 层,即最外层数组
|
||||
['deep'], // 数组中的数组,第 2 层
|
||||
let nestedArray = [ // top, or first level - the outer most array
|
||||
['deep'], // an array within an array, 2 levels of depth
|
||||
[
|
||||
['deeper'], ['deeper'] // 第 3 层,元素为嵌套的两个数组
|
||||
['deeper'], ['deeper'] // 2 arrays nested 3 levels deep
|
||||
],
|
||||
[
|
||||
[
|
||||
['deepest'], ['deepest'] // 第 4 层,元素为嵌套的两个数组
|
||||
['deepest'], ['deepest'] // 2 arrays nested 4 levels deep
|
||||
],
|
||||
[
|
||||
[
|
||||
['deepest-est?'] // 第 5 层,元素为嵌套的一个数组
|
||||
['deepest-est?'] // an array nested 5 levels deep
|
||||
]
|
||||
]
|
||||
]
|
||||
];
|
||||
```
|
||||
|
||||
虽然这个例子看起来错综复杂,不过,尤其是在处理大量数据的时候,这种数据结构还是经常会用到的。尽管结构复杂,不过我们仍可以通过方括号表示法来访问嵌套得最深的数组:
|
||||
While this example may seem convoluted, this level of complexity is not unheard of, or even unusual, when dealing with large amounts of data. However, we can still very easily access the deepest levels of an array this complex with bracket notation:
|
||||
|
||||
```js
|
||||
console.log(nestedArray[2][1][0][0][0]);
|
||||
// logs: deepest-est?
|
||||
```
|
||||
|
||||
既然我们知道数据的位置,当然,我们也可以修改它:
|
||||
And now that we know where that piece of data is, we can reset it if we need to:
|
||||
|
||||
```js
|
||||
nestedArray[2][1][0][0][0] = 'deeper still';
|
||||
@ -49,11 +49,11 @@ console.log(nestedArray[2][1][0][0][0]);
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个叫做 `myNestedArray` 的数组变量。请修改 `myNestedArray`,使用<dfn>字符串(string)</dfn>、<dfn>数字(number)</dfn>或<dfn>布尔值(boolean)</dfn>作为数组的元素,并让 `myNestedArray` 刚好有 5 层(注意,最外层的数组是第 1 层)。同时,请在第 3 层的数组中包含字符串 `'deep'`;在第 4 层的数组中包含字符串 `'deeper'`,在第 5 层的数组中包含字符串 `'deepest'`。
|
||||
We have defined a variable, `myNestedArray`, set equal to an array. Modify `myNestedArray`, using any combination of <dfn>strings</dfn>, <dfn>numbers</dfn>, and <dfn>booleans</dfn> for data elements, so that it has exactly five levels of depth (remember, the outer-most array is level 1). Somewhere on the third level, include the string `'deep'`, on the fourth level, include the string `'deeper'`, and on the fifth level, include the string `'deepest'`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myNestedArray` 中的数据元素应只包含字符串、数字或者布尔值。
|
||||
`myNestedArray` should contain only numbers, booleans, and strings as data elements
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -77,7 +77,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` 应刚好包含 5 层嵌套数组。
|
||||
`myNestedArray` should have exactly 5 levels of depth
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -100,7 +100,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` 中应只有一个字符串 `"deep"`,并且应出现在第 3 层数组中。
|
||||
`myNestedArray` should contain exactly one occurrence of the string `"deep"` on an array nested 3 levels deep
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -129,7 +129,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` 中应只有一个字符串 `"deeper"`,并且应出现在第 4 层数组中。
|
||||
`myNestedArray` should contain exactly one occurrence of the string `"deeper"` on an array nested 4 levels deep
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -158,7 +158,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` 中应只有一个字符串 `"deepest"`,并且应出现在第 5 层数组中。
|
||||
`myNestedArray` should contain exactly one occurrence of the string `"deepest"` on an array nested 5 levels deep
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1e
|
||||
title: 使用 Object.keys() 生成由对象的所有属性组成的数组
|
||||
title: Generate an Array of All Object Keys with Object.keys()
|
||||
challengeType: 1
|
||||
forumTopicId: 301160
|
||||
dashedName: generate-an-array-of-all-object-keys-with-object-keys
|
||||
@ -8,15 +8,15 @@ dashedName: generate-an-array-of-all-object-keys-with-object-keys
|
||||
|
||||
# --description--
|
||||
|
||||
我们可以给 `Object.keys()` 方法传入一个对象作为参数,这会返回一个由对象中所有属性(字符串)组成的数组。需要注意的是,数组中元素的顺序是不确定的。
|
||||
We can also generate an array which contains all the keys stored in an object using the `Object.keys()` method and passing in an object as the argument. This will return an array with strings representing each property in the object. Again, there will be no specific order to the entries in the array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
请完成 `getArrayOfUsers` 函数的实现,使其返回一个由输入对象中的所有属性所组成的数组。
|
||||
Finish writing the `getArrayOfUsers` function so that it returns an array containing all the properties in the object it receives as an argument.
|
||||
|
||||
# --hints--
|
||||
|
||||
`users` 对象应该只包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 这 4 个属性。
|
||||
The `users` object should only contain the keys `Alan`, `Jeff`, `Sarah`, and `Ryan`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -28,7 +28,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`getArrayOfUsers` 函数应返回一个包含 `users` 对象中所有属性的数组。
|
||||
The `getArrayOfUsers` function should return an array which contains all the keys in the `users` object
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b15
|
||||
title: 使用 for 循环遍历数组中的全部元素
|
||||
title: Iterate Through All an Array's Items Using For Loops
|
||||
challengeType: 1
|
||||
forumTopicId: 301161
|
||||
dashedName: iterate-through-all-an-arrays-items-using-for-loops
|
||||
@ -8,9 +8,9 @@ dashedName: iterate-through-all-an-arrays-items-using-for-loops
|
||||
|
||||
# --description--
|
||||
|
||||
使用数组时,我们经常需要遍历数组的所有元素来找出我们需要的一个或多个元素,抑或是对数组执行一些特定的操作。JavaScript 为我们提供了几个内置的方法,它们以不同的方式遍历数组,以便我们可以用于不同的场景(如 `every()`、`forEach()`、`map()` 等等)。然而,最简单的 `for` 循环不仅能实现上述这些方法的功能,而且相比之下也会更加灵活。
|
||||
Sometimes when working with arrays, it is very handy to be able to iterate through each item to find one or more elements that we might need, or to manipulate an array based on which data items meet a certain set of criteria. JavaScript offers several built in methods that each iterate over arrays in slightly different ways to achieve different results (such as `every()`, `forEach()`, `map()`, etc.), however the technique which is most flexible and offers us the greatest amount of control is a simple `for` loop.
|
||||
|
||||
请看以下的例子:
|
||||
Consider the following:
|
||||
|
||||
```js
|
||||
function greaterThanTen(arr) {
|
||||
@ -24,18 +24,18 @@ function greaterThanTen(arr) {
|
||||
}
|
||||
|
||||
greaterThanTen([2, 12, 8, 14, 80, 0, 1]);
|
||||
// 返回 [12, 14, 80]
|
||||
// returns [12, 14, 80]
|
||||
```
|
||||
|
||||
在这个函数中,我们用一个 `for` 循环来遍历数组,逐一对其中的元素进行判断。通过上面的代码,我们可以找出数组中大于 `10` 的所有元素,并返回一个包含这些元素的新数组。
|
||||
Using a `for` loop, this function iterates through and accesses each element of the array, and subjects it to a simple test that we have created. In this way, we have easily and programmatically determined which data items are greater than `10`, and returned a new array containing those items.
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了 `filteredArray` 函数,它接受一个嵌套的数组 `arr` 和一个 `elem` 作为参数,并要返回一个新数组。`arr` 数组中嵌套的数组里可能包含 `elem` 元素,也可能不包含。请修改该函数,用一个 `for` 循环来做筛选,使函数返回一个由 `arr` 中不包含 `elem` 的数组所组成的新数组。
|
||||
We have defined a function, `filteredArray`, which takes `arr`, a nested array, and `elem` as arguments, and returns a new array. `elem` represents an element that may or may not be present on one or more of the arrays nested within `arr`. Modify the function, using a `for` loop, to return a filtered version of the passed array such that any array nested within `arr` containing `elem` has been removed.
|
||||
|
||||
# --hints--
|
||||
|
||||
`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` 应返回 `[ [10, 8, 3], [14, 6, 23] ]`。
|
||||
`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` should return `[ [10, 8, 3], [14, 6, 23] ]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -54,7 +54,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2)` 应返回 `[ ["flutes", 4] ]`。
|
||||
`filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2)` should return `[ ["flutes", 4] ]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -70,7 +70,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")` 应返回 `[ ["amy", "beth", "sam"] ]`。
|
||||
`filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")` should return `[ ["amy", "beth", "sam"] ]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -85,7 +85,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` 应返回 `[]`。
|
||||
`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` should return `[ ]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -102,7 +102,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray` 函数中应使用 `for` 循环。
|
||||
The `filteredArray` function should utilize a `for` loop
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(filteredArray.toString().search(/for/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1d
|
||||
title: 使用 for...in 语句遍历对象
|
||||
title: Iterate Through the Keys of an Object with a for...in Statement
|
||||
challengeType: 1
|
||||
forumTopicId: 301162
|
||||
dashedName: iterate-through-the-keys-of-an-object-with-a-for---in-statement
|
||||
@ -8,25 +8,25 @@ dashedName: iterate-through-the-keys-of-an-object-with-a-for---in-statement
|
||||
|
||||
# --description--
|
||||
|
||||
如果我们想要遍历对象中的所有属性,只需要使用 JavaScript 中的 <dfn>for...in</dfn> 语句即可。以遍历 `users` 对象的属性为例:
|
||||
Sometimes you may need to iterate through all the keys within an object. This requires a specific syntax in JavaScript called a <dfn>for...in</dfn> statement. For our `users` object, this could look like:
|
||||
|
||||
```js
|
||||
for (let user in users) {
|
||||
console.log(user);
|
||||
}
|
||||
|
||||
// 输出:
|
||||
// logs:
|
||||
Alan
|
||||
Jeff
|
||||
Sarah
|
||||
Ryan
|
||||
```
|
||||
|
||||
在上面的代码中,我们定义了一个 `user` 变量。可以观察到,这个变量在遍历对象的 `for...in` 语句执行过程中会一直被重置并赋予新值,结果就是不同的用户名打印到了 console 中。**注意:**对象中的键是无序的,这与数组不同。因此,一个对象中某个属性的位置,或者说它出现的相对顺序,在引用或访问该属性时是不确定的。
|
||||
In this statement, we defined a variable `user`, and as you can see, this variable was reset during each iteration to each of the object's keys as the statement looped through the object, resulting in each user's name being printed to the console. **NOTE:** Objects do not maintain an ordering to stored keys like arrays do; thus a key's position on an object, or the relative order in which it appears, is irrelevant when referencing or accessing that key.
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个 `countOnline` 函数,请在其中使用 <dfn>for...in</dfn> 语句来遍历 `users` 对象中的用户,并返回 `online` 属性为 `true` 的用户数量。以下是一个传入 `countOnline` 函数的对象示例,注意每个用户都有 `online` 属性,其属性值为 `true` 或 `false`:
|
||||
We've defined a function `countOnline` which accepts one argument (a users object). Use a <dfn>for...in</dfn> statement within this function to loop through the users object passed into the function and return the number of users whose `online` property is set to `true`. An example of a users object which could be passed to `countOnline` is shown below. Each user will have an `online` property with either a `true` or `false` value.
|
||||
|
||||
```js
|
||||
{
|
||||
@ -44,29 +44,29 @@ Ryan
|
||||
|
||||
# --hints--
|
||||
|
||||
函数 `countOnline` 中应使用 `for in` 语句遍历传入的对象。
|
||||
The function `countOnline` should use a `for in` statement to iterate through the object keys of the object passed to it.
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(
|
||||
/for\s*\(\s*(var|let)\s+[a-zA-Z_$]\w*\s+in\s+[a-zA-Z_$]\w*\s*\)\s*{/
|
||||
/for\s*\(\s*(var|let|const)\s+[a-zA-Z_$]\w*\s+in\s+[a-zA-Z_$]\w*\s*\)/
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
当传入 `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }` 时,函数 `countOnline` 应该返回 `1`。
|
||||
The function `countOnline` should return `1` when the object `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }` is passed to it
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj1) === 1);
|
||||
```
|
||||
|
||||
当传入 `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }` 时,函数 `countOnline` 应该返回 `2`。
|
||||
The function `countOnline` should return `2` when the object `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }` is passed to it
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj2) === 2);
|
||||
```
|
||||
|
||||
当传入 `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }` 时,函数 `countOnline` 应该返回 `0`。
|
||||
The function `countOnline` should return `0` when the object `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }` is passed to it
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj3) === 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1f
|
||||
title: 修改存储在对象中的数组
|
||||
title: Modify an Array Stored in an Object
|
||||
challengeType: 1
|
||||
forumTopicId: 301163
|
||||
dashedName: modify-an-array-stored-in-an-object
|
||||
@ -8,21 +8,21 @@ dashedName: modify-an-array-stored-in-an-object
|
||||
|
||||
# --description--
|
||||
|
||||
我们已经学习了 JavaScript 对象的这些基本操作:添加、修改、移除键值对、检查某个属性是否存在、遍历对象的所有属性。在继续学习 JavaScript 的过程中,我们会了解对象的更多用法。另外,在之后的数据结构课程中,我们还会学习 ES6 的 <dfn>Map</dfn> 和 <dfn>Set</dfn>。这两种数据结构与我们现在学到的对象十分类似,但它们在对象的基础上提供了一些额外的功能。目前,我们已经学习了数组和对象的基础知识,让我们试着来用所学的知识解决一些更复杂的问题。
|
||||
Now you've seen all the basic operations for JavaScript objects. You can add, modify, and remove key-value pairs, check if keys exist, and iterate over all the keys in an object. As you continue learning JavaScript you will see even more versatile applications of objects. Additionally, the Data Structures lessons located in the Coding Interview Prep section of the curriculum also cover the ES6 <dfn>Map</dfn> and <dfn>Set</dfn> objects, both of which are similar to ordinary objects but provide some additional features. Now that you've learned the basics of arrays and objects, you're fully prepared to begin tackling more complex problems using JavaScript!
|
||||
|
||||
# --instructions--
|
||||
|
||||
请看一下代码编辑器中我们为你写好的对象。`user` 对象包含 3 个属性;`data` 对象包含 5 个属性,其中包含一个叫做 `friends` 的数组。这就是对象作为数据结构所展现出的灵活性。我们已经写好了 `addFriend` 函数的一部分,请你完成这个函数,使其接受一个 `user` 对象,将 `friend` 参数中的名字添加到 `user.data.friends` 数组中并返回该数组。
|
||||
Take a look at the object we've provided in the code editor. The `user` object contains three keys. The `data` key contains five keys, one of which contains an array of `friends`. From this, you can see how flexible objects are as data structures. We've started writing a function `addFriend`. Finish writing it so that it takes a `user` object and adds the name of the `friend` argument to the array stored in `user.data.friends` and returns that array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`user` 对象应该包含 `name`、`age` 和 `data` 三个属性。
|
||||
The `user` object should have `name`, `age`, and `data` keys.
|
||||
|
||||
```js
|
||||
assert('name' in user && 'age' in user && 'data' in user);
|
||||
```
|
||||
|
||||
`addFriend` 函数应该接受一个 `user` 对象和一个 `friend` 字符串作为输入参数,并将这个字符串插入到 `user` 对象的 `friends` 数组中。
|
||||
The `addFriend` function should accept a `user` object and a `friend` string as arguments and add the friend to the array of `friends` in the `user` object.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -35,7 +35,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`addFriend(user, "Pete")` 应该返回 `["Sam", "Kira", "Tomo", "Pete"]`。
|
||||
`addFriend(user, "Pete")` should return `["Sam", "Kira", "Tomo", "Pete"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b19
|
||||
title: 修改嵌套在对象中的对象
|
||||
title: Modify an Object Nested Within an Object
|
||||
challengeType: 1
|
||||
forumTopicId: 301164
|
||||
dashedName: modify-an-object-nested-within-an-object
|
||||
@ -8,7 +8,7 @@ dashedName: modify-an-object-nested-within-an-object
|
||||
|
||||
# --description--
|
||||
|
||||
现在我们来看一个稍复杂的对象。在对象中,我们也可以嵌套任意层数的对象,对象的属性值可以是 JavaScript 支持的任意类型,包括数组和其他对象。请看以下例子:
|
||||
Now let's take a look at a slightly more complex object. Object properties can be nested to an arbitrary depth, and their values can be any type of data supported by JavaScript, including arrays and even other objects. Consider the following:
|
||||
|
||||
```js
|
||||
let nestedObject = {
|
||||
@ -19,13 +19,14 @@ let nestedObject = {
|
||||
online: 80,
|
||||
onlineStatus: {
|
||||
active: 67,
|
||||
away: 13
|
||||
away: 13,
|
||||
busy: 8
|
||||
}
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
`nestedObject` 有 3 个属性:`id`(属性值为数字)、`date`(属性值为字符串)、`data`(属性值为嵌套的对象)。虽然对象中的数据可能很复杂,我们仍能使用上一个挑战中讲到的写法来访问我们需要的信息。如果我们想把嵌套在 `onlineStatus` 中 `busy` 的属性值改为 `10`,可以用点号表示法来这样实现:
|
||||
`nestedObject` has three properties: `id` (value is a number), `date` (value is a string), and `data` (value is an object with its nested structure). While structures can quickly become complex, we can still use the same notations to access the information we need. To assign the value `10` to the `busy` property of the nested `onlineStatus` object, we use dot notation to reference the property:
|
||||
|
||||
```js
|
||||
nestedObject.data.onlineStatus.busy = 10;
|
||||
@ -33,11 +34,11 @@ nestedObject.data.onlineStatus.busy = 10;
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个 `userActivity` 对象,它包含了另一个对象。请将 `online` 的属性值改为 `45`。
|
||||
Here we've defined an object `userActivity`, which includes another object nested within it. Set the value of the `online` key to `45`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`userActivity` 应包含 `id`、`date` 和 `data` 属性。
|
||||
`userActivity` should have `id`, `date` and `data` properties.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -45,19 +46,19 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`userActivity` 应包含 `data` 属性,其属性值应为包含 `totalUsers` 和 `online` 属性的对象。
|
||||
`userActivity` should have a `data` key set to an object with keys `totalUsers` and `online`.
|
||||
|
||||
```js
|
||||
assert('totalUsers' in userActivity.data && 'online' in userActivity.data);
|
||||
```
|
||||
|
||||
`userActivity` 的 `data` 属性值中的 `online` 属性值应被改为 `45`。
|
||||
The `online` property nested in the `data` key of `userActivity` should be set to `45`
|
||||
|
||||
```js
|
||||
assert(userActivity.data.online === 45);
|
||||
```
|
||||
|
||||
应使用点号表示法或方括号表示法来修改 `online` 属性值。
|
||||
The `online` property should be set using dot or bracket notation.
|
||||
|
||||
```js
|
||||
assert.strictEqual(code.search(/online: 45/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b0f
|
||||
title: 使用 pop() 和 shift() 从数组中删除元素
|
||||
title: Remove Items from an Array with pop() and shift()
|
||||
challengeType: 1
|
||||
forumTopicId: 301165
|
||||
dashedName: remove-items-from-an-array-with-pop-and-shift
|
||||
@ -8,35 +8,35 @@ dashedName: remove-items-from-an-array-with-pop-and-shift
|
||||
|
||||
# --description--
|
||||
|
||||
`push()` 和 `unshift()` 都有一个与它们作用相反的函数:`pop()` 和 `shift()`。与插入元素相反,`pop()` 会从数组的末尾*移除*一个元素,而 `shift()` 会从数组的开头移除一个元素。`pop()` 和 `shift()` 与 `push()` 和 `unshift()` 的关键区别在于,用于删除元素的方法不接收参数,而且每次只能删除数组中的一个元素。
|
||||
Both `push()` and `unshift()` have corresponding methods that are nearly functional opposites: `pop()` and `shift()`. As you may have guessed by now, instead of adding, `pop()` *removes* an element from the end of an array, while `shift()` removes an element from the beginning. The key difference between `pop()` and `shift()` and their cousins `push()` and `unshift()`, is that neither method takes parameters, and each only allows an array to be modified by a single element at a time.
|
||||
|
||||
让我们来看以下的例子:
|
||||
Let's take a look:
|
||||
|
||||
```js
|
||||
let greetings = ['whats up?', 'hello', 'see ya!'];
|
||||
|
||||
greetings.pop();
|
||||
// 数组现在是 ['whats up?', 'hello']
|
||||
// now equals ['whats up?', 'hello']
|
||||
|
||||
greetings.shift();
|
||||
// 数组现在是 ['hello']
|
||||
// now equals ['hello']
|
||||
```
|
||||
|
||||
这些用于删除数组元素的方法会返回被删除的元素:
|
||||
We can also return the value of the removed element with either method like this:
|
||||
|
||||
```js
|
||||
let popped = greetings.pop();
|
||||
// 返回 'hello',即 popped 的值为 'hello'
|
||||
// greetings 数组现在为 []
|
||||
// returns 'hello'
|
||||
// greetings now equals []
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个 `popShift` 函数,它接收一个数组作为输入参数并返回一个新的数组。请修改这个函数,使用 `pop()` 和 `shift()` 来移除输入的数组中的第一个元素和最后一个元素,并将这两个被移除的元素分别赋值给对应的变量,使得最终返回的数组里包含这两个值。
|
||||
We have defined a function, `popShift`, which takes an array as an argument and returns a new array. Modify the function, using `pop()` and `shift()`, to remove the first and last elements of the argument array, and assign the removed elements to their corresponding variables, so that the returned array contains their values.
|
||||
|
||||
# --hints--
|
||||
|
||||
`popShift(["challenge", "is", "not", "complete"])` 应返回 `["challenge", "complete"]`。
|
||||
`popShift(["challenge", "is", "not", "complete"])` should return `["challenge", "complete"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [
|
||||
@ -45,13 +45,13 @@ assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [
|
||||
]);
|
||||
```
|
||||
|
||||
`popShift` 函数中应使用 `pop()` 方法。
|
||||
The `popShift` function should utilize the `pop()` method
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1);
|
||||
```
|
||||
|
||||
`popShift` 函数中应使用 `shift()` 方法。
|
||||
The `popShift` function should utilize the `shift()` method
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b10
|
||||
title: 使用 splice() 删除元素
|
||||
title: Remove Items Using splice()
|
||||
challengeType: 1
|
||||
forumTopicId: 301166
|
||||
dashedName: remove-items-using-splice
|
||||
@ -8,40 +8,42 @@ dashedName: remove-items-using-splice
|
||||
|
||||
# --description--
|
||||
|
||||
在之前的挑战中,我们已经学习了如何用 `shift()` 和 `pop()` 从数组的开头或末尾移除元素。但如果我们想删除数组中间的一个元素,或者想一次删除多个元素,该如何操作呢?这时候我们就需要使用 `splice()` 方法了,`splice()` 可以让我们从数组中的任意位置**连续删除任意数量的元素**。
|
||||
Ok, so we've learned how to remove elements from the beginning and end of arrays using `shift()` and `pop()`, but what if we want to remove an element from somewhere in the middle? Or remove more than one element at once? Well, that's where `splice()` comes in. `splice()` allows us to do just that: **remove any number of consecutive elements** from anywhere in an array.
|
||||
|
||||
`splice()` 最多可以接受 3 个参数,但现在我们先关注前两个。`splice()` 接收的前两个参数以调用 `splice()` 数组中的元素索引作为参考。别忘了,数组的索引是*从 0 开始的*,所以我们要用 `0` 来表示数组中的第一个元素。`splice()` 的第一个参数代表从数组中的哪个索引开始移除元素,而第二个参数表示要从数组中的这位位置删除多少个元素。例如:
|
||||
`splice()` can take up to 3 parameters, but for now, we'll focus on just the first 2. The first two parameters of `splice()` are integers which represent indexes, or positions, of the array that `splice()` is being called upon. And remember, arrays are *zero-indexed*, so to indicate the first element of an array, we would use `0`. `splice()`'s first parameter represents the index on the array from which to begin removing elements, while the second parameter indicates the number of elements to delete. For example:
|
||||
|
||||
```js
|
||||
let array = ['today', 'was', 'not', 'so', 'great'];
|
||||
|
||||
array.splice(2, 2);
|
||||
// 从索引为 2 的位置(即第三个元素)开始移除 2 个元素
|
||||
// array 的值现在是 ['today', 'was', 'great']
|
||||
// remove 2 elements beginning with the 3rd element
|
||||
// array now equals ['today', 'was', 'great']
|
||||
```
|
||||
|
||||
`splice()` 不仅会修改调用该方法的数组,还会返回一个包含被移除元素的数组:
|
||||
`splice()` not only modifies the array it's being called on, but it also returns a new array containing the value of the removed elements:
|
||||
|
||||
```js
|
||||
let array = ['I', 'am', 'feeling', 'really', 'happy'];
|
||||
|
||||
let newArray = array.splice(3, 2);
|
||||
// newArray 的值是 ['really', 'happy']
|
||||
// newArray equals ['really', 'happy']
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了数组 `arr`。请使用 `splice()` 从 `arr` 里移除元素,使剩余的元素之和为 `10`。
|
||||
We've initialized an array `arr`. Use `splice()` to remove elements from `arr`, so that it only contains elements that sum to the value of `10`.
|
||||
|
||||
# --hints--
|
||||
|
||||
不应修改这一行 `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`。
|
||||
You should not change the original line of `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`.
|
||||
|
||||
```js
|
||||
assert(code.replace(/\s/g, '').match(/constarr=\[2,4,5,1,7,5,2,1\];?/));
|
||||
assert(
|
||||
__helpers.removeWhiteSpace(code).match(/constarr=\[2,4,5,1,7,5,2,1\];?/)
|
||||
);
|
||||
```
|
||||
|
||||
`ahr` 的剩余元素之和应为 `10`。
|
||||
`arr` should only contain elements that sum to `10`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -50,16 +52,18 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
应对 `arr` 调用 `splice()` 方法。
|
||||
Your code should utilize the `splice()` method on `arr`.
|
||||
|
||||
```js
|
||||
assert(code.replace(/\s/g, '').match(/arr\.splice\(/));
|
||||
assert(__helpers.removeWhiteSpace(code).match(/arr\.splice\(/));
|
||||
```
|
||||
|
||||
splice 应只删除 `arr` 里面的元素,不能给 `arr` 添加元素。
|
||||
The splice should only remove elements from `arr` and not add any additional elements to `arr`.
|
||||
|
||||
```js
|
||||
assert(!code.replace(/\s/g, '').match(/arr\.splice\(\d+,\d+,\d+.*\)/g));
|
||||
assert(
|
||||
!__helpers.removeWhiteSpace(code).match(/arr\.splice\(\d+,\d+,\d+.*\)/g)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7e367417b2b2512b20
|
||||
title: 使用数组存储不同类型的数据
|
||||
title: Use an Array to Store a Collection of Data
|
||||
challengeType: 1
|
||||
forumTopicId: 301167
|
||||
dashedName: use-an-array-to-store-a-collection-of-data
|
||||
@ -8,15 +8,15 @@ dashedName: use-an-array-to-store-a-collection-of-data
|
||||
|
||||
# --description--
|
||||
|
||||
以下是最简单的<dfn>数组(Array)</dfn>示例:这是一个<dfn>一维数组(one-dimensional array)</dfn>,它只有一层,或者说它里面没有包含其它数组。可以观察到,这个数组中只包含了<dfn>布尔值(booleans)</dfn>、<dfn>字符串(strings)</dfn>、<dfn>数字(numbers)</dfn>以及 JavaScript 中的其他数据类型:
|
||||
The below is an example of the simplest implementation of an array data structure. This is known as a <dfn>one-dimensional array</dfn>, meaning it only has one level, or that it does not have any other arrays nested within it. Notice it contains <dfn>booleans</dfn>, <dfn>strings</dfn>, and <dfn>numbers</dfn>, among other valid JavaScript data types:
|
||||
|
||||
```js
|
||||
let simpleArray = ['one', 2, 'three', true, false, undefined, null];
|
||||
console.log(simpleArray.length);
|
||||
// 输出 7
|
||||
// logs 7
|
||||
```
|
||||
|
||||
所有数组都有一个表示长度的属性,我们可以通过 `Array.length` 来访问它。接下来是一个稍复杂的数组示例:这是一个<dfn>多维数组(multi-dimensional Array)</dfn>,或者说是一个包含了其他数组的数组。可以观察到,在这个数组内部还包含了 JavaScript 的<dfn>对象(objects)</dfn>,我们会在后面的挑战中详细讨论该数据结构。现在,你只需要知道数组能够存储复杂的对象数据。
|
||||
All arrays have a length property, which as shown above, can be very easily accessed with the syntax `Array.length`. A more complex implementation of an array can be seen below. This is known as a <dfn>multi-dimensional array</dfn>, or an array that contains other arrays. Notice that this array also contains JavaScript <dfn>objects</dfn>, which we will examine very closely in our next section, but for now, all you need to know is that arrays are also capable of storing complex objects.
|
||||
|
||||
```js
|
||||
let complexArray = [
|
||||
@ -45,35 +45,35 @@ let complexArray = [
|
||||
|
||||
# --instructions--
|
||||
|
||||
我们已经定义了一个名为 `yourArray` 的变量。请修改代码,将一个含有至少 5 个元素的数组赋值给 `yourArray` 变量。你的数组中应包含至少一个 <dfn>string</dfn> 类型的数据、一个 <dfn>number</dfn> 类型的数据和一个 <dfn>boolean</dfn> 类型的数据。
|
||||
We have defined a variable called `yourArray`. Complete the statement by assigning an array of at least 5 elements in length to the `yourArray` variable. Your array should contain at least one <dfn>string</dfn>, one <dfn>number</dfn>, and one <dfn>boolean</dfn>.
|
||||
|
||||
# --hints--
|
||||
|
||||
yourArray 应为数组。
|
||||
`yourArray` should be an array.
|
||||
|
||||
```js
|
||||
assert.strictEqual(Array.isArray(yourArray), true);
|
||||
```
|
||||
|
||||
`yourArray` 应包含至少 5 个元素。
|
||||
`yourArray` should be at least 5 elements long.
|
||||
|
||||
```js
|
||||
assert.isAtLeast(yourArray.length, 5);
|
||||
```
|
||||
|
||||
`yourArray` 应包含至少一个 `boolean`。
|
||||
`yourArray` should contain at least one `boolean`.
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'boolean').length >= 1);
|
||||
```
|
||||
|
||||
`yourArray` 应包含至少一个 `number`。
|
||||
`yourArray` should contain at least one `number`.
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'number').length >= 1);
|
||||
```
|
||||
|
||||
`yourArray` 应包含至少一个 `string`。
|
||||
`yourArray` should contain at least one `string`.
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'string').length >= 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b1b
|
||||
title: 使用 delete 关键字删除对象属性
|
||||
title: Use the delete Keyword to Remove Object Properties
|
||||
challengeType: 1
|
||||
forumTopicId: 301168
|
||||
dashedName: use-the-delete-keyword-to-remove-object-properties
|
||||
@ -8,11 +8,11 @@ dashedName: use-the-delete-keyword-to-remove-object-properties
|
||||
|
||||
# --description--
|
||||
|
||||
现在我们已经学习了什么是对象以及对象的基本特性和用途。总之,对象是以键值对的形式,灵活、直观地存储结构化数据的一种方式,***而且***,通过对象的属性查找属性值是速度很快的操作。在本章余下的挑战中,我们来了解一下对象的几种常用操作,这样你能更好地在代码中使用这个十分有用的数据结构:对象。
|
||||
Now you know what objects are and their basic features and advantages. In short, they are key-value stores which provide a flexible, intuitive way to structure data, ***and***, they provide very fast lookup time. Throughout the rest of these challenges, we will describe several common operations you can perform on objects so you can become comfortable applying these useful data structures in your programs.
|
||||
|
||||
在之前的挑战中,我们已经试过添加和修改对象中的键值对。现在我们来看看如何从一个对象中*移除*一个键值对。
|
||||
In earlier challenges, we have both added to and modified an object's key-value pairs. Here we will see how we can *remove* a key-value pair from an object.
|
||||
|
||||
我们再来回顾一下上一个挑战中的 `foods` 对象。如果我们想移除 `apples` 属性,可以像这样使用 `delete` 关键字:
|
||||
Let's revisit our `foods` object example one last time. If we wanted to remove the `apples` key, we can remove it by using the `delete` keyword like this:
|
||||
|
||||
```js
|
||||
delete foods.apples;
|
||||
@ -20,11 +20,11 @@ delete foods.apples;
|
||||
|
||||
# --instructions--
|
||||
|
||||
请使用 `delete` 关键字来移除 `foods` 中的 `oranges`、`plums` 和 `strawberries` 属性。
|
||||
Use the delete keyword to remove the `oranges`, `plums`, and `strawberries` keys from the `foods` object.
|
||||
|
||||
# --hints--
|
||||
|
||||
`foods` 对象应只包含 3 个属性:`apples`、`grapes` 和 `bananas`。
|
||||
The `foods` object should only have three keys: `apples`, `grapes`, and `bananas`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -35,7 +35,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
应使用 `delete` 关键字来移除 `oranges`、`plums` 和 `strawberries` 属性。
|
||||
The `oranges`, `plums`, and `strawberries` keys should be removed using `delete`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
Reference in New Issue
Block a user