mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-04-18 01:00:50 -04:00
* feat(tools): add seed/solution restore script * chore(curriculum): remove empty sections' markers * chore(curriculum): add seed + solution to Chinese * chore: remove old formatter * fix: update getChallenges parse translated challenges separately, without reference to the source * chore(curriculum): add dashedName to English * chore(curriculum): add dashedName to Chinese * refactor: remove unused challenge property 'name' * fix: relax dashedName requirement * fix: stray tag Remove stray `pre` tag from challenge file. Signed-off-by: nhcarrigan <nhcarrigan@gmail.com> Co-authored-by: nhcarrigan <nhcarrigan@gmail.com>
2.1 KiB
2.1 KiB
id, title, challengeType, forumTopicId, dashedName
| id | title | challengeType | forumTopicId | dashedName |
|---|---|---|---|---|
| 587d7b87367417b2b2512b42 | 改变一个用 const 声明的数组 | 1 | 301206 | mutate-an-array-declared-with-const |
--description--
在现代的 JavaScript 里,const声明有很多用法。
一些开发者倾向默认使用const来声明所有变量,但如果它们打算在后续的代码中修改某个值,那在声明的时候就会用let。
然而,你要注意,对象(包括数组和函数)在使用const声明的时候依然是可变的。使用const来声明只会保证它的标识不会被重新赋值。
"use strict";
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]
从以上代码看出,你可以改变[5, 6, 7]自身,所以s变量指向了改变后的数组[5, 6, 45]。和所有数组一样,数组s中的数组元素是可以被改变的,但是因为使用了const关键字,你不能使用赋值操作符将变量标识s指向另外一个数组。
--instructions--
这里有一个使用const s = [5, 7, 2]声明的数组。使用对各元素赋值的方法将数组改成[2, 5, 7]。
--hints--
不要替换const关键字。
(getUserInput) => assert(getUserInput('index').match(/const/g));
s应该为常量 (通过使用const)。
(getUserInput) => assert(getUserInput('index').match(/const\s+s/g));
不要改变原数组的声明。
(getUserInput) =>
assert(
getUserInput('index').match(
/const\s+s\s*=\s*\[\s*5\s*,\s*7\s*,\s*2\s*\]\s*;?/g
)
);
s应该等于[2, 5, 7]。
assert.deepEqual(s, [2, 5, 7]);
--seed--
--seed-contents--
const s = [5, 7, 2];
function editInPlace() {
// Only change code below this line
// Using s = [2, 5, 7] would be invalid
// Only change code above this line
}
editInPlace();
--solutions--
const s = [5, 7, 2];
function editInPlace() {
s[0] = 2;
s[1] = 5;
s[2] = 7;
}
editInPlace();