ES6 & String,Array Method

wonkeunC·2021년 3월 26일
0

JavaScript

목록 보기
4/15
post-thumbnail

Bye ES5 👋

Hello ES6

Class 지원
let & const 문법 추가
Arrow Functions
Modules
Promises / Async Await
구조분해할당 (Destructuring)
기본 매개변수 (Default Parameter)
Rest Parameter / argument (유사배열)
Spread Operator
Import / Export
Template Strings : `${_}`
객체 리터럴



ES6 String 메서드


includes()

배열이 특정 요소를 포함하고 있는지 판별합니다.

🧩 문자안에 특정 값이 있는지 점검하기.

let isEmail = email => email.includes("@");

console.log(isEmail("dbk03053@naver.com"));
// 출력 : true

console.log(isEmail("dbk03053naver.com"));
// 출력 : false

repeat()

문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환합니다.

🧩 반복되는 문자를 처리하기
ex : #######3068

const CC_NUMBER = "3068";

const displayNumber = `${"#".repeat(7)} ${CC_NUMBER}`;

console.log(displayNumber);
// 출력 : #######3068

startsWith() / endsWith()

startsWith() : 어떤 문자열이 특정 문자로 시작하는지 확인하여 결과를 true 혹은 false로 반환합니다.
endsWith() : 어떤 문자열에서 특정 문자열로 끝나는지를 확인할 수 있으며, 그 결과를 true 혹은 false로 반환한다.

🧩 문자열의 시작값 / 마지막값 여부 확인하기

startsWith()

const name = "Mr.Choi";

console.log(name.startsWith("Mr"));
// 출력 : true

console.log(name.startsWith("Choi"));
// 출력 : false

endsWith() : 이메일 .com 으로 끝나는지 확인 할 수 있다.

console.log(name.endsWith("Mr"));
// 출력 : false

console.log(name.endsWith("Choi"));
// 출력 : true



ES6 Array 메서드


Array.from() <-- 중요!

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


여기서 NodeList(6) 는 배열이 아닌 "유사배열" 이다.

<button>에 class를 붙쳐줘도 마찬가지다.


HTMLCollection(6) 또한 배열처럼 보이는 유사배열이다.

무수히 많은 <button>이 있다고 가정해보자!
모든 <button>에 어떠한 기능을 적용 시키고 싶은데 forEach(), Map() 이러한 메서드를 사용할 수 없다.
왜냐하면 <button>은 유사배열이지 배열이 아니기 때문이다.


💡 그렇기 때문에 Array.from() 을 사용해줘야 한다 !

방법 1


let buttons = document.getElementsByClassName('btn');

Array.from(buttons).forEach(item => {
    item.addEventListener("click",() => console.log("눌렸어염"))
})

방법 2

let buttons = document.getElementsByClassName('btn');

let magicBox = Array.from(buttons);

magicBox.forEach(item => {
    item.addEventListener("click",() => console.log("눌렸어염"))
})

👇👇👇 결과 👇👇👇

정리 : Array.from()은 object-like-array를 array로 바꿔주는 메서드이다.
굉장히 유익한 메서드이니 반드시 기억하고
있자!


Array.of()

인자의 수나 유형에 관계없이 가변 인자를 갖는 새 Array 인스턴스를 만듭니다.
배열에 element가 많을때 Array.of()를 사용하면 유익하다.

🧩

const friends = ["won","jae","seung","phn"]; <-- 예전 방식

const friends = Array.of("won","jae","seung","phn"); <-- 새로운 방식


Array.find()

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

const number = Array.of("10","20","30","50","75");

let answer = number.find(item => item > 30);

console.log(answer)
// 50  <-- 30 보다 큰 값 중에 첫 번째 요소의 값

배열 element 중에 특정 값을 포함한 element 를 찾고 싶을때.
let email = Array.of("d52@naver.com","dh2@gmail.com","whl@yahoo.com","psa@gmail.com")

let answer = email.find(item => item.includes("@yahoo.com"));

console.log(answer);
// whl@yahoo.com

Array.findIndex()

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

let email = Array.of("d52@naver.com","dh2@gmail.com","whl@yahoo.com","psa@gmail.com")

let answer = email.findIndex(item => item.includes("@yahoo.com"));

console.log(answer);
// 2  

0 : "d52@naver.com"
1 : "dh2@gmail.com"
2 : "whl@yahoo.com" <--

error 이메일을 수정하기

let email = Array.of("d52@naver.com","dh2@gmail.com","whl@error.com","psa@gmail.com")

let target = email.findIndex(item => item.includes("@error.com"));

let username = email[target].split("@")[0];
// "whl"

const fixedEmail = "naver.com";

email[target] = `${username}@${fixedEmail}`

console.log(email);


Array.fill()

배열의 시작 인덱스부터 끝 인덱스의 이전까지 정적인 값 하나로 채웁니다.


profile
개발자로 일어서는 일기

0개의 댓글