Jun

只要我的心還會跳,腿還能動

我就沒有理由停下前進的步伐

ES6 縮寫與解構賦值


縮寫

const kakashi = '卡卡西';
const partner = {
  naruto: '鳴人',
  sasuke: '佐助',
  sakura: '小櫻',
};

const seventhClass = {
  kakashi,
  partner,
};

console.log(seventhClass);

// {
//   kakashi: '卡卡西',
//   partner: { naruto: '鳴人', sasuke: '佐助', sakura: '小櫻' }
// }
const kakashi = '卡卡西';
const partner = {
  naruto: '鳴人',
  sasuke: '佐助',
  sakura: '小櫻',
};

const seventhClass = {
  kakashi,
  ...partner,
};

console.log(seventhClass);

// {
//   kakashi: '卡卡西',
//   naruto: '鳴人',
//   sasuke: '佐助',
//   sakura: '小櫻'
// }

解構賦值

let arr = [1, 2, 3];
let [one, two, three] = arr;

console.log(one, two, three); // 1 2 3
let one = 2;
let two = 1;
[one, two] = [two, one];

console.log(one, two); // 1 2
let str = '安安你好嗎';
let [a, b, c, d, e] = str;

console.log(a, b, c, d, e); // 安 安 你 好 嗎
let partner = {
  naruto: '鳴人',
  sasuke: '佐助',
  sakura: '小櫻',
};

let { sakura } = partner;
console.log(sakura); // 小櫻

let { naruto: ohMyGod } = partner;
console.log(ohMyGod); // 鳴人
let [one = 3, two = 2] = [1];

console.log(one, two); // 1 2

let { one = 2, two = 2 } = { one: 1 };

console.log(one, two); // 1 2
let [x, ...y] = [1, 2, 3];

console.log(x, y); // 1 [ 2, 3 ]