2.3 KiB
2.3 KiB
id, challengeType, forumTopicId, title
id | challengeType | forumTopicId | title |
---|---|---|---|
587d7b87367417b2b2512b43 | 1 | 301211 | 使用箭头函数编写简洁的匿名函数 |
Description
const myFunc = function() {
const myVar = "value";
return myVar;
}
ES6 提供了其他写匿名函数的方式的语法糖。你可以使用箭头函数:
const myFunc = () => {
const myVar = "value";
return myVar;
}
当不需要函数体,只返回一个值的时候,箭头函数允许你省略return
关键字和外面的大括号。这样就可以将一个简单的函数简化成一个单行语句。
const myFunc = () => "value";
这段代码仍然会返回value
。
Instructions
magic
函数,使其返回一个新的Date()
。同时不要用var
关键字来定义任何变量。
Tests
tests:
- text: 替换掉<code>var</code>关键字。
testString: getUserInput => assert(!getUserInput('index').match(/var/g));
- text: <code>magic</code>应该为一个常量 (使用<code>const</code>)。
testString: getUserInput => assert(getUserInput('index').match(/const\s+magic/g));
- text: <code>magic</code>是一个<code>function</code>。
testString: assert(typeof magic === 'function');
- text: <code>magic()</code>返回正确的日期。
testString: assert(magic().setHours(0,0,0,0) === new Date().setHours(0,0,0,0));
- text: 不要使用<code>function</code>关键字。
testString: getUserInput => assert(!getUserInput('index').match(/function/g));
Challenge Seed
var magic = function() {
"use strict";
return new Date();
};
Solution
const magic = () => {
"use strict";
return new Date();
};