개인노트-인강

개인노트 nomad ES6의 정석 #4 Array

roroism 2023. 2. 3. 18:25

# 4.0 Array.from() and Array.of()

 

##  Array.of()

 

Array.of() 메서드는 인자의 수나 유형에 관계없이 가변 인자를 갖는 새 Array 인스턴스를 만듭니다.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/of

const friends1 = ["nico", "lynn", "dal", "mark"];

const friends2 = Array.of("nico", "lynn", "dal", "mark");

element가 많을 때 사용하면 좋습니다.

 

## Array.from()

 

Array.from() 메서드는 유사 배열 객체(array-like object)나 반복 가능한 객체(iterable object)를 얕게 복사해 새로운Array 객체를 만듭니다.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/from

<html>
    <body>
    <button>1</button>
    <button>2</button>
    <button>3</button>
    <button>4</button>
    <button>5</button>
    <button>6</button>
    <button>7</button>
    <button>8</button>
    <button>9</button>
    <button>10</button>
    </body>
</html>

각각의 버튼에 이벤트 리스너를 연결할 경우..

const buttons = document.querySelectorAll("button");

console.log(buttons);
// 출력 결과
// NodeList(10)

출력된 NodeList가 array인 것 같지만, 사실 array는 아닙니다.

 

아래처럼 class를 추가한 경우에는..

<html>
    <body>
    <button class="btn">1</button>
    <button class="btn">2</button>
    <button class="btn">3</button>
    <button class="btn">4</button>
    <button class="btn">5</button>
    <button class="btn">6</button>
    <button class="btn">7</button>
    <button class="btn">8</button>
    <button class="btn">9</button>
    <button class="btn">10</button>
    </body>
</html>
const buttons = document.getElementsByClassName("btn");

console.log(buttons);
// 출력 결과
// HTMLCollection(10)

HTMLCollection이라는 것이 나옵니다. array같지만 array는 아닙니다.

 

이런 것을 array-like object라고 부릅니다. array같지만 array는 아닙니다.

array가 아니라서 할 수 없는 것이 있습니다.

const buttons = document.getElementsByClassName("btn");

console.log(buttons);
// 출력 결과
// HTMLCollection(10)

buttons.forEach(button => {
	button.addEventListener("click", () => console.log("I ve been clicked"));
});

array라면 forEach가 사용되어야 되지만 에러가 발생합니다.

 

Array.from()을 사용해서 array로 바꿔줄 수 있습니다.

const buttons = document.getElementsByClassName("btn");

console.log(buttons);
// 출력 결과
// HTMLCollection(10)

Array.from(buttons).forEach(button => {
	button.addEventListener("click", () => console.log("I ve been clicked"));
});

메소드 설명에도 Creates an array from array-like object. 라고 나옵니다.

 

이처럼 가끔 HTML을 다룰 때, array를 얻지 못하고 array-like object를 반환받으면 Array.from() 을 사용하여 array로 바꿀 수 있습니다.

array-like object를 만나면 .from() 을 사용하여 array로 변경합시다.

 

# 4.1 Array.find()       Array.findIndex()       Array.fill()

 

## Array.prototype.find()

 

find() 메서드는 주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환합니다.
그런 요소가 없다면 undefined를 반환합니다.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/find

 

const friends = [
    "nico@gmail.com",
    "lynn@naver.com",
    "dal@yahoo.com",
    "mark@hotmail.com",
    "flynn@korea.com",
];

const target = friends.find(friend => friend.includes("@korea.com"));

console.log(target);
// 결과
// "flynn@korea.com"

 

## Array.prototype.findIndex()

 

가끔은 element 가 아니라 element 가 어디있는지 알고 싶을 때가 있습니다.

찾아서 수정을 해야할 경우에는 index를 알아야합니다.

 

findIndex() 메서드는 주어진 판별 함수를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환합니다.
만족하는 요소가 없으면 -1을 반환합니다.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

 

const friends = [
    "nico@gmail.com",
    "lynn@naver.com",
    "dal@yahoo.com",
    "mark@hotmail.com",
    "flynn@gorea.com",
];

const check = () => friends.findIndex((friend) => friend.includes("gorea.com"));

let target = check();

if (target !== -1) {
    console.log(target);
    // 결과
    // 4

    // 수정
    const username = friends[target].split("@")[0];

    const email = "korea.com"

    friends[target] = `${username}@${email}`;

    target = check();
}

console.log(target);
// 결과
// -1

 

## Array.prototype.fill()

 

fill() 메서드는 배열의 시작 인덱스부터 끝 인덱스의 이전까지 정적인 값 하나로 채웁니다.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/fill

 

const friends = [
    "nico@gmail.com",
    "lynn@naver.com",
    "dal@yahoo.com",
    "mark@hotmail.com",
    "flynn@gorea.com",
];

const check = () => friends.findIndex((friend) => friend.includes("gorea.com"));

let target = check();

if(target !== -1) {
	friends.fill("*".repeat(5), 1, 3);
}
// 결과
// 0: "nico@gmail.com"
// 1: "*****"
// 2: "*****"
// 3: "mark@hotmail.com"
// 4: "flynn@gorea.com"