* 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 |
---|---|---|---|---|
598f48a36c8c40764b4e52b3 | 防止对象改变 | 1 | 301207 | prevent-object-mutation |
--description--
通过之前的挑战可以看出,const
声明并不会真的保护你的数据不被改变。为了确保数据不被改变,JavaScript 提供了一个函数Object.freeze
来防止数据改变。
当一个对象被冻结的时候,你不能再对它的属性再进行增、删、改的操作。任何试图改变对象的操作都会被阻止,却不会报错。
let obj = {
name:"FreeCodeCamp",
review:"Awesome"
};
Object.freeze(obj);
obj.review = "bad"; // will be ignored. Mutation not allowed
obj.newProp = "Test"; // will be ignored. Mutation not allowed
console.log(obj);
// { name: "FreeCodeCamp", review:"Awesome"}
--instructions--
在这个挑战中,你将使用Object.freeze
来防止数学常量被改变。你需要冻结MATH_CONSTANTS
对象,使得没有人可以改变PI
的值,抑或增加或删除属性。
--hints--
不要替换const
关键字。
(getUserInput) => assert(getUserInput('index').match(/const/g));
MATH_CONSTANTS
应该为一个常量 (使用const
)。
(getUserInput) =>
assert(getUserInput('index').match(/const\s+MATH_CONSTANTS/g));
不要改变原始的MATH_CONSTANTS
。
(getUserInput) =>
assert(
getUserInput('index').match(
/const\s+MATH_CONSTANTS\s+=\s+{\s+PI:\s+3.14\s+};/g
)
);
PI
等于3.14
。
assert(PI === 3.14);
--seed--
--seed-contents--
function freezeObj() {
const MATH_CONSTANTS = {
PI: 3.14
};
// Only change code below this line
// Only change code above this line
try {
MATH_CONSTANTS.PI = 99;
} catch(ex) {
console.log(ex);
}
return MATH_CONSTANTS.PI;
}
const PI = freezeObj();
--solutions--
function freezeObj() {
const MATH_CONSTANTS = {
PI: 3.14
};
Object.freeze(MATH_CONSTANTS);
try {
MATH_CONSTANTS.PI = 99;
} catch(ex) {
console.log(ex);
}
return MATH_CONSTANTS.PI;
}
const PI = freezeObj();