Methods 및 문법
Array.from()
유사 배열 객체나 반복 가능한 객체를 복사해 새로운 배열을 만든다.
console.log(Array.from('foo'));
console.log(Array.from([1, 2, 3], x => x + x));
console.log(Array.from(Array(5), (v, i) => i + 1));
.charCodeAt() / .charAt() / String.fromCharCode()
해당 변수의 ()안 인덱스 값에 해당하는 문자의 아스키 코드를 출력한다. (인덱스는 띄어쓰기도 센다.)String.fromCharCode()는 해당 아스키코드를 가진 문자를 가져온다.const string = 'Hi my name is';
console.log(string.charCodeAt(6), string.charAt(6));
console.log(String.fromCharCode(97));
.concat()
두 배열을 합칠 수 있다.const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6, 7];
console.log(arr1.concat(arr2));
.fill()
파라미터 안의 숫자로 배열안의 값을 채운다.const array1 = [1, 2, 3, 4];
console.log(array1.fill(0, 2, 4));
console.log(array1.fill(5, 1));
console.log(array1.fill(6));
.filter()
조건에 부합하는 배열 요소만을 반환한다.map과 문법이 같다.const numbers = [1, 2, 3, 4, 5, 6];
arr = numbers.filter((item, index, arr) => {
console.log(item, index, arr);
return item > 3;
});
console.log(arr);
간단하게 다음처럼 작성할 수 있다.const numbers = [1, 2, 3, 4, 5, 6];
arr = numbers.filter(num => num > 3);
console.log(arr);
find / findIndex
find는 배열에 특정 값이 있는지 찾고 반환한다.findIndex는 배열에 특정 값이 있는지 찾고 위치를 반환한다.const fruits = ["Apple", "Banana", "Cherry"];
const result = fruits.findIndex(item => {
return item === "Apple";
});
console.log(result);
정규식과 함께 이런식으로 사용할 수 있다.const fruits = ["Apple", "Banana", "Cherry"];
const result1 = fruits.find(item => {
return /^A/.test(item);
})
const result2 = fruits.findIndex(item => {
return /^C/.test(item);
})
console.log(result1);
console.log(result2);
for…of 명령문
배열뿐 아니라 Map, Set, String 등에도 사용이 가능하다.const arr = ['a', 'b', 'c'];
for (const element of arr) {
console.log(element);
}
forEach 문
배열에만 적용이 가능하다.괄호 안 세가지 인수는 요소 값, 해당 요소의 인덱스, 순회 중인 배열이다.const array = ['a', 'b', 'c'];
array.forEach((el, idx, arr) => {
console.log(el, idx, arr)
});
for…in 문
모든 객체에 적용 가능하다. 객체의 키 값을 순회한다.배열에 적용하면 키 값을 인덱스 번호로 한다.enumerable 속성이 true인 것만 순회한다.enumerable은 객체의 숨겨진 속성 중 하나로 브라우저에 console.log를 찍어보면 알 수 있다. (enumerable: 셀 수 있는, 열거할 수 있는)const object = { a: 1, b: 2, c: 3 };
for (const key in object) {
console.log(`${key}: ${object[key]}`);
}
.includes()
배열이 ()안의 요소를 포함하고 있는지 판별한다.const array1 = [1, 2, 3];
console.log(array1.includes(2));
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
console.log(pets.includes('at'));
.indexOf() / .lastIndexOf()
const arr = [1, 2, 3, 4, 1, 2];
arr.indexOf(3)
arr.indexOf(1)
arr.indexOf(6)
배열에서 ()안의 값이 있는 인덱스 번호를 알려준다.isNaN()
isNaN(NaN);
isNaN(undefined);
isNaN({});
isNaN(true);
isNaN(null);
isNaN(37);
isNaN("37");
isNaN("37.37");
isNaN("123ABC");
isNaN("");
isNaN(" ");
isNaN(new Date());
isNaN(new Date().toString());
()안의 데이터가 숫자로 변환된다면 false를, 숫자로 변환되지 않는 값이면 true를 리턴한다..join()
배열의 모든 element를 연결해 하나의 문자열을 만든다. ()안의 내용을 사이에 넣는다.()안에 아무것도 없을 경우 ,를 넣는다.따라서 사이에 아무 내용 없이 붙이려면 “”를 입력해야 한다.const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join());
console.log(elements.join(''));
console.log(elements.join('-'));
.length
배열의 길이를 알려준다. length는 직접 조작이 가능하다.const arr = [1, 2, 3, 4, 5];
console.log(arr.length);
.map()
배열의 모든 인덱스를 순회하며 해당 함수를 적용한다.원본 배열에 영향을 미치지 않는다. (변경하지 않는다)const fruits = ["사과", "파인애플", "오렌지", "수박"];
fruits.map(function(item, index, originArr) {
console.log(item, index, originArr);
})
화살표 함수로는 다음과 같이 사용할 수 있다.const fruits = ["사과", "파인애플", "오렌지", "수박"];
fruits.map((item, index, originArr) => {
console.log(item, index, originArr);
})
숫자에 사용하려면 아래와 같이 사용할 수 있다.map함수는 리턴값을 배열로 만들어준다.const nums = [1, 2, 3, 4, 5, 6];
const newNums = nums.map((item, index, originArr) => {
return item * 2;
});
console.log(newNums);
이를 간단하게 표현하면 아래처럼 사용할 수 있다.const nums = [1, 2, 3, 4, 5, 6];
const newNums = nums.map(x => x*2);
console.log(newNums);
중괄호 내부에 return외에 코드가 없을 때는 중괄호와 return을 함께 생략할 수 있다.또한 파라미터가 하나라면 괄호를 생략할 수 있다.Map 객체
Map 객체는 ES6에서 도입된 데이터 구조이다.이는 키와 값을 서로 매핑(연결)시켜 저장된 순서대로 각 요소들을 접근할 수 있도록 한다.여기에는 .set(), .get(), .has(), .delete() 등의 메소드가 존재하고 그 역할과 사용법은 아래와 같다.let sayings = new Map();
sayings.set("dog", "woof");
sayings.set("cat", "meow");
sayings.set("elephant", "toot");
console.log(sayings.size);
console.log(sayings.get("fox"));
console.log(sayings.get("cat"));
console.log(sayings.has("bird"));
sayings.delete("dog");
console.log(sayings)
for (let [key, value] of sayings) {
console.log(key + " goes " + value);
}
Math.max() / Math.min()
스프레드 연산자를 이용하여 해당 배열의 가장 큰 수 또는 가장 작은 수를 찾을 수 있다.const arr = [1, 2, 3, 4, 5];
const maxValue = Math.max(...arr);
const minValue = Math.min(...arr);
console.log(Math.max(-1, 2, 4))
Math.abs()
절댓값을 리턴한다.const num = -999;
console.log(Math.abs(num));
Math.ceil() / Math.floor() / Math.round()
순서대로 올림, 내림, 반올림이다.console.log(Math.ceil(3.14));
console.log(Math.floor(3.14));
console.log(Math.round(3.6));
console.log(Math.round(3.4));
Math.random()
0에서 1사이의 난수를 생성한다.아래 처럼 하면 일정 범위 내의 난수를 생성할 수 있다.
const ranNum = Math.floor(Math.random() * 100);
console.log(ranNum);
Object.keys() / Object.values()
객체 안의 key 또는 value 데이터를 배열로 반환한다.const obj = {
name: "경은",
age: 26,
address: "seoul"
};
console.log(Object.keys(obj));
console.log(Object.values(obj));
Object.assign()
객체의 병합에 사용되는 메소드obj1과 returnObj는 메모리 주소가 같다.const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const returnObj = Object.assign(obj1, obj2);
console.log(obj1);
console.log(obj2);
console.log(returnObj);
Optional Chaining (?, 물음표)
옵셔널 체이닝을 사용하면 undefined에 어떠한 메소드를 실행해도 TypeError가 뜨지 않고 undefined를 리턴한다.값이 누락될 가능성이 있는 경우 이를 사용하면 프로그램의 안정성을 높일 수 있다.const obj = {
name: '경은',
age: 27,
address: 'seoul'
}
console.log(obj.height);
console.log(obj.height.length);
console.log(obj.height?.length);
padstart(), padEnd()
padStart(문자열 길이, 채울 문자)padStart()는 앞의 문자열을 입력한 문자열 길이만큼 특정 문자로 앞부분을 채워준다.