개발/Javascript
[ES6] String, Array 관련 함수(spread) 추가 정리
yunzema
2019. 12. 24. 11:49
반응형
기본적인 내용은 제외하고, 개인적으로 기록하고픈 내용들만 정리한다.
1. String
1) startsWith() , endsWith() : 앞/뒤로 일치하는 문자열 판단
2) includes() : 문자열 포함여부 판단
let str = "A is B";
str.startsWith("A"); //true
str.endsWith("B"); //true
str.includes("is"); //true
2. Array
1) for in의 문제 보완한 for of
//for-in의 경우 index로 순회 : 상위 prototype의 값도 포함될 수 있음
let data = ["A","B"];
Array.prototype.getIndex = "C";
for(let index in data){
console.log(data[index]); //"A", "B", "C"
}
//for-of의 경우 value 순회가능
let data = ["A", "B"];
Array.prototype.getIndex = "C";
for(let value of data){
console.log(value); //"A", "B"
}
2) spread 연산자
[ ... array ] 배열또는 iterable을 "개별" 요소로 분리
- 기본 예제
// 배열
console.log(...[1, 2, 3]); // -> 1, 2, 3
// 문자열
console.log(...'Helllo'); // H e l l l o
// Map과 Set
console.log(...new Map([['a', '1'], ['b', '2']])); // [ 'a', '1' ] [ 'b', '2' ]
console.log(...new Set([1, 2, 3])); // 1 2 3
- 배열 합치기 예제
const a = [1,2,3];
const b = [4,5];
const c = ["안녕"];
car d = a.concat(b,c); //기존 ES5 방식
const d = [...a, ...b, c]; //기존 ES6 방식
console.log(d); //[1,2,3,4,5,"안녕"]
- 원본 배열 유지 예제
const a = [1,2,3,4,5];
//const b = a.reverse(); //ES5 기존 방식
const b = [...a].reverse();
console.log(a); //1,2,3,4,5
console.log(b); //5,4,3,2,1
- 나머지 요소 할당
const a = [1,2,3,4,5];
let [first, second, ...rest] = a;
console.log(first, second, rest); //1 2 [3,4,5]
- 객체에서 사용
const obj1 = {x:1, y:2};
const obj2 = {...obj1, z:3};
console.log(obj2); //{x:1, y:2, z:3}