時隔 6 年在 2015 年推出的 ES6 出現了許多影響現代 Coding 的功能,這邊來慢慢介紹吧
if (true) {
let x = 10; // x 只在這個 if 塊內有效
var y = 20; // y 在整個函數或全局範圍內有效
}
console.log(x); // ReferenceError: x is not defined
console.log(y); // 輸出: 20
const name = "john";
const greeting = `Heelo, ${name}!`;
const templateString = `
Hello,
Emma
` // '\nHello,\nEmma\n'
const add = (a, b) => a + b
// 同等於
const addOldFunc = function(a, b){
return a + b
}
// math.js
export const add = (a, b) => a + b;
// main.js
import { add } from './math';
console.log(add(2, 3));
const obj = { a: 1, b: 2 };
const { a, b } = obj;
const arr = [1, 2, 3];
const [x, y] = arr;
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched");
}, 1000);
});
};
fetchData().then(data => console.log(data));