str.padStart(targetLength [, padString])
padEnd() 도 있다. 채워넣기는 대상 문자열의 끝(우측)부터 적용됨const ddayTxt = document.querySelector(".dDay");
function calcDate() {
const today = new Date();
const christmas = new Date(2022, 11, 25).getTime();
const todayMs = today.getTime();
const leftMs = christmas - todayMs;
let leftDay = Math.floor(leftMs / (1000 * 60 * 60 * 24));
let leftHour = String(
Math.floor((leftMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
).padStart(2, 0);
let leftMinute = String(
Math.floor((leftMs % (1000 * 60 * 60)) / (1000 * 60))
).padStart(2, 0);
let leftSecond = String(Math.floor((leftMs % (1000 * 60)) / 1000)).padStart(
2,
0
);
ddayTxt.innerText = `${leftDay}d ${leftHour}h ${leftMinute}m ${leftSecond}s`;
}
calcDate();
setInterval(calcDate, 1000);
너저분.... 내가 봐도 지저분하니 조만간 정리 해볼 예정ㅎㅎ...
// 이전 방식
var x = 1, y = 2;
var obj = {
x: x,
y: y
};
console.log(obj); // { x: 1, y: 2 }
// ES6
let x = 1, y = 2;
const obj = { x, y };
console.log(obj); // { x: 1, y: 2 }
// ES6 Destructuring
const arr = [1, 2, 3];
// 배열의 인덱스를 기준으로 배열로부터 요소를 추출하여 변수에 할당
// 변수 one, two, three가 선언되고 arr(initializer(초기화자))가
// Destructuring(비구조화, 파괴)되어 할당된다.
const [one, two, three] = arr;
// 디스트럭처링을 사용할 때는 반드시 initializer(초기화자)를 할당해야 한다.
// const [one, two, three];
// SyntaxError: Missing initializer in destructuring declaration
console.log(one, two, three); // 1 2 3
배열 디스트럭처링을 위해서는 할당 연산자 왼쪽에 배열 형태의 변수 리스트가 필요하다
let x, y, z;
[x, y] = [1, 2];
console.log(x, y); // 1 2
[x, y] = [1];
console.log(x, y); // 1 undefined
[x, y] = [1, 2, 3];
console.log(x, y); // 1 2
[x, , z] = [1, 2, 3];
console.log(x, z); // 1 3
// 기본값
[x, y, z = 3] = [1, 2];
console.log(x, y, z); // 1 2 3
[x, y = 10, z = 3] = [1, 2];
console.log(x, y, z); // 1 2 3
// spread 문법
[x, ...y] = [1, 2, 3];
console.log(x, y); // 1 [ 2, 3 ]

요러케 변수끼리 값을 스왑하기가 개쉬워진다. (출처 : 한입 크기로 잘라 먹는 어쩌고 강의)
// 두 번째 요소는 필요하지 않음
let [firstName, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
alert( title ); // Consul
정리하다가 신기해서 가져옴 자바스크립트는 참 유연하구나...
좀 알게 됐다 싶으면 고양이 마냥 액체처럼 흘러내리는 느낌 (╯°□°)╯︵ ┻━┻
// ES6 Destructuring
const obj = { firstName: 'Ungmo', lastName: 'Lee' };
// 프로퍼티 키를 기준으로 디스트럭처링 할당이 이루어진다. 순서는 의미가 없다.
// 변수 lastName, firstName가 선언되고 obj(initializer(초기화자))가 Destructuring(비구조화, 파괴)되어 할당된다.
const { lastName, firstName } = obj;
console.log(firstName, lastName); // Ungmo Lee
const todos = [
{ id: 1, content: 'HTML', completed: true },
{ id: 2, content: 'CSS', completed: false },
{ id: 3, content: 'JS', completed: false }
];
// todos 배열의 요소인 객체로부터 completed 프로퍼티만을 추출한다.
const completedTodos = todos.filter(({ completed }) => completed);
console.log(completedTodos); // [ { id: 1, content: 'HTML', completed: true } ]
이전에 인강으로 봤던 개념임에도 불구하고 볼 때마다 새로운 디스트럭처링과 객체 리터럴... 응용 잘하면 겁나 멋질 것 같은데 생각이 잘 안 난다...