解构赋值
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 = {...}