// bad (albeit way faster)
const arr = [1, 2, 3, 4];
const len = arr.length;
var i = -1;
var result = [];
while (++i < len) {
var n = arr[i];
if (n % 2 > 0) continue;
result.push(n * n);
}
// good
const arr = [1, 2, 3, 4];
const isEven = n => n % 2 == 0;
const square = n => n * n;
const result = arr.filter(isEven).map(square);
为了快速上手这个列子,我们打开FireFox的代码速记工具Scratchpad(在开发者工具里面,快捷键 shift+F4).
ctrl+R运行后报错误:TypeError:redeclaration of …
在这个网站,给了我一个提示,原来需要使用严格模式。http://stackoverflow.com/questions/22603078/syntaxerror-use-of-const-in-strict-mode
在前面加上 'use strict' 就能解决此问题。