2.9 KiB
2.9 KiB
id, title, challengeType, forumTopicId, localeTitle
id | title | challengeType | forumTopicId | localeTitle |
---|---|---|---|---|
5a661e0f1068aca922b3ef17 | Access an Array's Contents Using Bracket Notation | 1 | 301149 | 使用方括号访问数组的内容 |
Description
let ourArray = ["a", "b", "c"];
在一个数组结构中,其内部的每个元素都有一个与之对应的索引(index)。索引是该元素在数组中的位置,可被用于引用该元素。但需要注意的是,JavaScript 数组的索引是从0开始的(zero-indexed),即一个数组的第一个元素是在数组中的第 0 个位置,而不是第 1 个位置。
要从一个数组中获取一个元素,我们可以在一个数组变量名的后面加一个使用“方括号”括起来的索引。这叫做方括号符号(bracket notation)。
例如我们要从ourArray
数组变量中获取数据元素"a"
并将其赋值给一个变量,我们可以编写如下所示的代码:
let ourVariable = ourArray[0];
// ourVariable 的值为 "a"
除了使用 “索引” 来获取某个元素值以外,你还可以通过类似的方法来设置一个索引位置所对应的元素值:
ourArray[1] = "not b anymore";
// ourArray 现在的值为 ["a", "not b anymore", "c"];
我们现在已经利用方括号将索引为 1 的元素从"b"
设置为了"not b anymore"
。
Instructions
myArray
中第二个元素(索引1
)设置为除了"b"
以外的任意值。
Tests
tests:
- text: '<code>myArray[0]</code>等于<code>"a"</code>'
testString: assert.strictEqual(myArray[0], "a");
- text: '<code>myArray[1]</code>不再设置为<code>"b"</code>'
testString: assert.notStrictEqual(myArray[1], "b");
- text: '<code>myArray[2]</code>等于<code>"c"</code>'
testString: assert.strictEqual(myArray[2], "c");
- text: '<code>myArray[3]</code>等于<code>"d"</code>'
testString: assert.strictEqual(myArray[3], "d");
Challenge Seed
let myArray = ["a", "b", "c", "d"];
// change code below this line
//change code above this line
console.log(myArray);
Solution
// solution required
let myArray = ["a", "b", "c", "d"];
myArray[1] = "e";