JavaScript:淺談ES6常見縮寫
818 字,約 1 分鐘
🌟 ES6 語法糖:不會影響運作,邏輯與當前 JS 一致
物件內的函式
const obj = {
hello: function() {
return "hello world";
}
}
obj.hello()
顯示如下
hello world
ES6 縮寫(去除 funtion)
const obj = {
hello() {
return "hello world";
}
}
obj.hello()
顯示如下
hello world
物件內變數
const A = 100
const B = {"A": A}
顯示如下
{A:100}
ES6 縮寫(將同名變數僅寫一個)
const A = 100
const C = {A}
顯示如下
{A:100}
- 這樣的效果跟原本{"A": A}一樣
物件展開-陣列相加
const groupA = ['A', 'B', 'C'];
const groupB = ['D', 'E'];
const groupAll = groupA.concat(groupB);
顯示如下
['A', 'B', 'C', 'D', 'E']
ES6 陣列相加縮寫
- 能夠透過...的方式代表陣列展開的形式
const groupA = ['A', 'B', 'C'];
const groupB = ['D', 'E'];
const groupAll = [...groupA, ...groupB]
顯示如下
['A', 'B', 'C', 'D', 'E']
ES6 物件展開
- 新增一個物件包含新方法,同時加入原有的方法
const methods = {
fn1() {
console.log(1);
},
fn2() {
console.log(2);
},
}
const newmethod = {
test(){
console.log("test")
},
...methods
}
newmethod.fn1()
留言
留言使用 GitHub 帳號登入(Giscus),留言會存在 GitHub Discussions。