ES6是 ECMAScript 2015 的簡稱,是 JavaScript 的重大版本更新。
從這個版本開始,語言變得更強大,也更容易閱讀與維護。
屬於區塊範疇(block scope)。
let name = "Kenneth";
name = "Leo"; // 可以重新指派
let name = "John"; // 無法重複宣告
屬於區塊範疇(block scope)。
const PI = 3.14;
PI = 3.14159; // 無法重新指派
const city; // 必須同時賦值
const fruitGroup = {
dragonfruit: "火龍果",
apple: "蘋果",
};
fruitGroup.banana = "香蕉"; // 仍可新增屬性
console.log(a); // ReferenceError
let a = 5;
遞迴指的是「函式呼叫自身」。
function sum(n) {
if (n === 1) return 1;
return n + sum(n - 1);
}
console.log(sum(5)); // 15
// 傳統寫法
function test(n) {
return n;
}
// 匿名函式
const test = function(n) {
return n;
};
// 箭頭函式
const test = (n) => {
return n;
};
// 若只有一個參數可簡寫
const test = n => n;
var arr = [1, 2, 3, 4, 5];
console.log(
arr
.filter(value => value > 1)
.map(value => value * 2)
);
// [4,6,8,10]
ES6 原生支援模組化語法。
export 用來匯出模組,import 用來引入模組。
// 方式一
export function add(a, b) {
return a + b;
}
export const PI = 3.14;
// 方式二
function add(a, b) { return a + b; }
const PI = 3.14;
export { add, PI };
// 方式三(預設輸出)
export default function add(a, b) {
return a + b;
}
// 對應方式一、二
import { add, PI } from './utils.js';
console.log(add(3,5), PI);
// 匯入預設
import add from './utils.js';
// 匯入全部
import * as utils from './utils.js';
console.log(utils.add(3,5), utils.PI);
Template Literal 使用反引號(`)來包住字串。
function sayHi(name) {
console.log(`Hello, ${name}, now is ${new Date()}`);
}
sayHi(`Nick`);
多行字串範例:
var str = `
hey
hi
yo
ya
`;
console.log(str);
先前寫法:
console.log('Hello, ' + name + ' now is ' + new Date());
現代寫法:
console.log(`Hello, ${name}, now is ${new Date()}`);