0%

六角線上研討會-ES6~11用一次就上癮的語法

`星爆!物件迴圈屌屌跑

傳統做法 for…in
Object.keys, Object.values

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const family = {
ming: {
name: '小明',
},
jay: {
name: '杰倫',
},
casper: {
name: '卡斯伯',
}
}
// ====
console.log(Object.values(family));
Object.values(family).forEach(item => {
console.log(item);
});
console.log(Object.keys(family));
Object.keys(family).forEach((key) => {
console.log(key, family[key]);
})

可選串聯

關鍵字 optional chaining(可選串連)
不確定屬性是否存在,物件如何取得深層值而不出錯
let obj = {
family: {
name: ‘’
}
}
console.log(obj?.family?.name);

空位合併(ES11)

1
2
3
4
5
function fn(a) {
const newValue = a ?? 100;
console.log(newValue);
}
fn(null);

參數預設值

1
2
3
4
function fn(a = 100) {
console.log(a);
}
fn(0);

戰鬥力超過 1000000000000000000000! 大數值計算

1
console.log(NUMBER.MAX_SAFE_INTEGER); //JS能計算最大數

關鍵字 BigInt

Vue3 的秘密,Proxy

傳統做法 defineProperty

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const obj = {
a: '',
value: {
}
};
Object.defineProperty(obj, 'a', {
get() {
console.log('getter');
return this.value.a;
},
set(value) {
// console.log('setter', value);
this.value.a = value;
const app = document.querySelector('#app');
app.innerHTML = this.value.a
}
});
obj.a = 1;
console.log(obj.a);

使用proxy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const handler = {
get(target, prop) {
console.log('getter', target, prop);
return target[prop]
},
set(obj, prop, value) {
console.log('setter', obj, prop, value)
obj[prop] = value;
const app = document.querySelector('#app');
app.innerHTML = obj[prop]
return true;
}
}
const obj = new Proxy({}, handler)
obj.a = 1;
console.log(obj.a);