ES6+ Array 관련 메소드를 알아보자
Array.of(element)
Array.of는 ( )안 요소를 배열로 바꿔준다
const arr = Array.of(1, 2, 3);
console.log(arr); // [1, 2, 3]
Array.from(iterable object(ArrayLike))
Array.from은 ( )안 iterable object(ArrayLike)를 Array로 변환시켜준다
const buttons = document.getElementsByClassName("btn");
console.log(buttons); // HTMLCollection [button.btn, button.btn, button.btn]
buttons.forEach((btn) =>
btn.addEventListener("click", () => console.log("click!")) // 오류
);
Array.from(buttons).forEach(
(btn) => btn.addEventListener("click", () => console.log("click!")) // 잘 실행 된다
);
⭐️ 중요 메소드!
find(function)
find는 판별함수를 만족하는 첫 요소의 값을 반환한다
const animals = ["cat", "dog", "chicken", "tiger", "deer", "bear"];
const todayAnimal = animals.find((e) => e.includes("e"));
console.log(todayAnimal); // "chicken"
findIndex(function)
findIndex는 판별함수를 만족하는 첫 요소의 인덱스를 반환한다
const animals = ["cat", "dog", "chicken", "tiger", "deer", "bear"];
const todayAnimal = animals.findIndex((e) => e.includes("e"));
console.log(todayAnimal); // 2
fill(value, startIdx, endIdx)
fill은 시작 인덱스부터 끝 인덱스까지 정적 값으로 채운다
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.fill(7, 0, 3)); // [7, 7, 7, 4, 5]
// endIdx 생략
console.log(numbers.fill(7, 2)); // [1, 2, 7, 7, 7]
// startIdx 생략
console.log(numbers.fill(7)); // [7, 7, 7, 7, 7]
startIdx, endIdx는 생략가능하다
끝! 😌