解構賦值
Node.js 解構賦值
取得陣列指定位置資料
let Employee = ['Kay', 'Jay'];
let [Kay, Jay] = Employee;
// [ 'Kay', 'Jay' ]
console.log(Employee);
// Kay
console.log(Kay);
// Jay
console.log(Jay);
取得陣列指定位置資料,忽略其中幾個數值
沒有要指定的資料,使用 逗號隔開但留空
,不指定變數
let Employee = ['Kay', 'Jay'];
let [, Jay] = Employee;
// [ 'Kay', 'Jay' ]
console.log(Employee);
// Jay
console.log(Jay);
單行定義變數
不建議使用,當變數越多,導致程式可讀性不高
let [Kay, Jay] = ['Kay', 'Jay'];
// Kay
console.log(Kay);
// Jay
console.log(Jay);
交換變數數值
let name = 'KJ';
let age = 17;
// My name is KJ, my age is 17
console.log(`My name is ${name}, my age is ${age}`);
// 交換變數數值
[name, age] = [age, name];
// My name is 17, my age is KJ
console.log(`My name is ${name}, my age is ${age}`);
取得物件中指定鍵值的變數值
const Employee = {
name : 'KJ',
age: 17
};
// 取得物件中指定鍵值的變數值
const {name, age} = Employee;
// { name: 'KJ', age: 17 }
console.log(Employee);
// KJ
console.log(name);
// 17
console.log(age);
物件屬性賦值
若鍵值相同,直接將變數傳入物件中,變數名稱即為鍵值名稱
const name = 'KJ';
const age = 17;
let Employee = {
name,
age
};
// { name: 'KJ', age: 17 }
console.log(Employee);
若鍵值有要異動,則就在前方加入鍵值名稱即可
const name = 'KJ';
const age = 17;
let Employee = {
newName : name,
age
};
// { newName: 'KJ', age: 17 }
console.log(Employee);
取得指定數值,並重設其他屬性到新變數
const Employee = {
name : 'KJ',
age: 17,
height: 199
};
// 取得指定數值,並重設其他屬性到新變數
const {age, ...OtherEmployee} = Employee;
// 17
console.log(age);
// { name: 'KJ', height: 199 }
console.log(OtherEmployee);
// { name: 'KJ', age: 17, height: 199 }
console.log(Employee);
用於傳遞物件參數
const SayHi = ({name, ...other}) => {
// KJ
console.log(name);
// { age: 17, height: 199 }
console.log(other);
};
SayHi({
name : 'KJ',
age: 17,
height: 199
})
擴展物件數值
const Employee = {
name : 'KJ',
age: 17,
};
const NewEmployee = {
...Employee,
height: 199
};
// { name: 'KJ', age: 17 }
console.log(Employee);
// { name: 'KJ', age: 17, height: 199 }
console.log(NewEmployee);
連續等於
會先從 後面
賦值,才往前賦值
NewEmployee = Employee = Person = {...}