반응형

ES6 새로운 기능들을 알아보겠다.
1. let, const 키워드
let, const 키워드를 사용하여 블록 스코프의 변수를 선언할 수 있다.
- let : 재선언X , 재할당O
- const : 재선언X , 재할당X
const A = "first const";
let a = "first let";
{//블록 스코프이므로 블록 안에서만 유효
const A = "block const A";
console.log(A); // block const A
let a = "block let a";
console.log(a); // block let a
}
console.log(A); // first const
console.log(a); // first let
//let a = "a 재선언" <= 재선언시 에러
a = "a 재할당 가능";
console.log(a); // a 재할당 가능
2. 화살표 함수
아래와 같은 형태로 기존보다 간단히 작성할 수 있다.
// ES5
var x = function(x, y) {
return x * y;
}
// ES6
const x = (x, y) => x * y;
3. 템플릿 리터럴
ES5와는 다르게 백틱(` `) 내에서 변수 및 줄바꿈을 할 수 있다.
변수는 백틱 내에서 ${ } 기호로 감싸서 사용한다.
const ES5_TEXT = 'ES5';
const ES6_TEXT = 'ES6';
// ES5
var es5_str = ES5_TEXT + ' 입니다.' + '\n줄바꿈 입니다.';
console.log(es5_str);
// ES6
var es6_str = `${ES6_TEXT} 입니다.
줄바꿈 입니다.`;
console.log(es6_str);
ES5 입니다.
줄바꿈 입니다.
ES6 입니다.
줄바꿈 입니다.
4. for/of 문
const brand = ["Benz", "BMW", "Audi"];
let text = "";
for (let x of brand) {
text += x + " ";
}
console.log(text); // Benz BMW Audi
5. String.includes(), String.startsWith(), String.endsWith() 메서드
- String.includes() : 문자열을 포함하는지
- String.startsWith() : 문자열로 시작하는지
- String.endsWith() : 문자열로 끝나는지
let text = "Hello world";
console.log(text.includes("world")); // true
console.log(text.startsWith("Hello")); // true
console.log(text.endsWith("world")); // true
6. Array.from(), Array keys(), Array find(), Array findIndex() 메서드
- Array.from() : 문자열을 하나씩 잘라 배열로 만듦
- Array keys() : Array Iterator 객체를 만듦
- Array find() : 함수를 통과하는 첫 번째 배열 요소의 값을 반환
- Array findIndex() : 함수를 통과하는 첫 번째 배열 요소의 인덱스를 반환
// 1. Array.from()
var str = "SCHOOL";
Array.from(str); // ['S', 'C', 'H', 'O', 'O', 'L']
// 2. Array keys()
var fruits = ["Apple", "Banana", "Orange"];
var keys = fruits.keys();
var text = "";
for (var x of keys) {
console.log(x); // 0 1 2
}
// 3. Array find()
// 4. Array findIndex()
const numbers = [2, 4, 10, 25, 50];
let findResult = numbers.find(callback);
let findIndexResult = numbers.findIndex(callback);
function callback(value, index, array) {
console.log("index : " + index + ", value : " + value);
/*
index : 0, value : 4
index : 1, value : 9
index : 2, value : 16
index : 3, value : 25
*/
return value > 20;
}
console.log(findResult); // 25
console.log(findIndexResult); // 3반응형
'개발 > JavaScript' 카테고리의 다른 글
| [JavaScript] 문자열 자르기 substring, substr, slice (0) | 2022.01.10 |
|---|---|
| [JavaScript] URL과 텍스트를 SNS(Facebook, Twitter, Pinterest) / Email(mailto) 로 공유 (0) | 2021.10.18 |