[JS] ES6 - Array

[JS] ES6 - Array

이채현

Array

Array.of()

무엇이든 Array로 만들어준다.

1
2
3
4
// Array.of()
const alphabet = ["a", "b", "c", "d"];
const alphabet = Array.of("a", "b", "c", "d")const alphabet = Array.of("a", "b", "c", "d", 1, 2, 3);;
console.log(alphabet);

Array.from()

Array.from(array같이 생긴 것)

😠 querySelectorgetElementbyClassName으로 엘리먼트 찾으면 array 같지만 아닌 다른 저장 포맷으로 저장된다

array-like object를 array로 바꿔준다.

1
2
3
4
5
6
7
8
9
10
11
const buttons = document.getElementsByClassName("btn");
console.log(buttons);
// buttons는 Array가 아니기 때문에
// 아래와 같이 forEach를 사용할 수 없다.
buttons.forEach((button) => {
button.addEventListener("click", () => console.log("I ve been clickeds"));
});
----------------
Array.from(buttons).forEach((button) => {
button.addEventListener("click", () => console.log("I ve been clickeds"));
});

Array.find()

Array.prototype.find() - JavaScript | MDN

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* Array.find()
*/
const friends = [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
];

const target1 = friends.find((friend) => friend.includes("@yahoo.com"));
// 조건을 넣어주면 forEach를 돌리면서 그에 맞는 값을 리턴해준다
// 찾은 첫번째 값만 반환해준다
// 없으면 undefined반환한다
console.log(target1);

Array.findIndex()

Array.prototype.findIndex() - JavaScript | MDN

1
2
3
4
5
6
7
8
9
10
/**
* Array.findIndex()
*/
const target2 = friends.findIndex((friend) => friend.includes("@yahoo.com"));
// 인덱스가 필요할때!
// 없으면 -1반환한다
console.log(target2);
const userName = friends[target2].split("@")[0];
const email = "yahoo.com";
console.log(`${userName}@${email}`);

Array.fill()

Array.prototype.fill() - JavaScript | MDN

1
2
3
4
5
if (target2 !== -1) {
friends.fill("*".repeat(5), target2 + 1);
// target부터 모든 변수는 다 채울값으로 채워줌
}
console.log(friends);
Author

Chaehyeon Lee

Posted on

2022-01-01

Updated on

2022-06-26

Licensed under

댓글