ReasonJun

javascript : spread / destructing assignment 본문

Frontend/Javasciprt

javascript : spread / destructing assignment

ReasonJun 2023. 6. 7. 01:21
728x90

spread

const a = [1, 2, 3];

console.log(...a); // 1 2 3

const b = [4, 5, 6];

const c = a.concat(b);
console.log(c); // [ 1, 2, 3, 4, 5, 6 ]

const d = [a, b];
console.log(d); // [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]

const e = [...a, ...b];
console.log(e); // [ 1, 2, 3, 4, 5, 6 ]

const aa = { x: 1, y: 2 };
const bb = { y: 3, z: 4 };

const cc = Object.assign({}, aa, bb);
console.log(cc); // { x: 1, y: 3, z: 4 }

const dd = { aa, bb };
console.log(dd); // { aa: { x: 1, y: 2 }, bb: { y: 3, z: 4 } }

const ee = { ...aa, ...bb };
console.log(ee); // { x: 1, y: 3, z: 4 }

// Object

const youjun = { name: 'youjun', age: 26, home: { address: 'home' } };
const updated = {
  ...youjun,
  job: 's/w engineer',
};
console.log(youjun); // { name: 'youjun', age: 26, home: { address: 'home' } }
console.log(updated);
/**
{
  name: 'youjun',
  age: 26,
  home: { address: 'home' },
  job: 's/w engineer'
}
*/


function fn(x, y, z) {
  console.log(x, y, z);
}

fn(1, 2, 3); // 1 2 3

const aaa = [1, 2, 3];
fn(aaa); // [ 1, 2, 3 ] undefined undefined
fn(...aaa); // 1 2 3

destructing assignment

const arr = [1, 2, 3];
const a = arr[0];
const b = arr[1];
const c = arr[2];

console.log(a, b, c); // 1 2 3

const [aa, bb, cc] = arr;

console.log(aa, bb, cc); // 1 2 3

const point = [1, 2];
const [y, x, z = 0] = point;
console.log(x); // 2
console.log(y); // 1
console.log(z); // 0

function createEmoji() {
  return ['apple', '🍎'];
}
const [title, emoji] = createEmoji();
console.log(title); // apple
console.log(emoji); // 🍎

let qq = 0;
let ww = 0;

const arr1 = [1, 2, 3];

[, , ee] = arr;
console.log(ee); // 3

const arr2 = [1, 2, 3];
const [zz, ...rest] = arr2;
console.log(a, rest); // 1 [ 2, 3 ]

//

const obj = {
  a1: 1,
  b1: 2,
  c1: 3,
  x: 7,
  y: 100,
};
// Data can be found directly by attribute name.
const { a1, b1 } = obj;
console.log(a1, b1); // 1 2

const { x = 4, a1: you, y: ten = 10 } = obj;
console.log(x, you, ten); // 7 1 100 => 4 if there is no x data, 100 if there is no y data


const prop = {
  name: 'Button',
  styles: {
    size: 28,
    color: 'yellow',
  },
};

function changeColor({ styles: { color } }) {
  console.log(color);
  console.log(styles); // An error occurs, because it is only used for destructuring assignment, not a variable
}
changeColor(prop);
728x90

'Frontend > Javasciprt' 카테고리의 다른 글

javascript : module  (0) 2023.06.07
Javascript : Operators Basic  (0) 2023.06.07
Javascript : Loop  (1) 2023.06.07
javascript : built-in object [array]  (0) 2023.06.07
Javascript : Function  (2) 2023.06.07
Comments