-
[TIL] 01.02카테고리 없음 2024. 1. 2. 20:48
ES6
1) var, let, const
var a=1;
var a=2; // var 은 선언을 다시 할 수 있음. /
let a=1;
a=2;
let은 선언을 다시하면 오류가 나고, 재할당은 가능/
2) arrow function
function add () {
}
var add = function () {
}
var add = (x) => {
return 1;
}
var add = x =>1;
3) 삼항 연산자
condition ? true 인 경우 : false 인 경우
console.log (true ? "참" : "거짓") // 참
console.log (false ? "참" : "거짓") // 거짓
console.log (1===1 ? "참" : "거짓") // 참
console.log (1 !== 1 ? "참" : "거짓") // 거짓
구조분해할당 : de(=not) + structure (구조) / 배열이나, 객체의 속성을 해체하는 것
(1) 배열의 경우
let [value1, value2] = [1, "new"];
let arr = ["value1", "value2", "value3"];
let [a, b, c, d] = arr;
console.log(a); // value1
console.log(d); // undefined
(2) 객체의 경우
let user = {
name : "nbc",
age : 30,
};
let {name, age} = user
console.log(name); // nbc
- 새로운 이름으로 할당하기
let { name, age, birthday = "today" } = user;
console.log(name); // nbc
console.log(age); // 30
console.log(birthday); // today ,
(초기값 설정인 today 로 나오나 객체에서 birthday: yesterday 등의 할당값이 있을 경우, 그 값이 나온다.)
// 단축 속성명 : property shorthand
const name = 'nbc';
const age = '30';
// key- value 값이 같으면 생략이 가능하다.
const obj = { name, age } ;
// 전개 구문 = spread operator (...)
let arr = [ 1, 2, 3 ];
let newArr = [...arr , 4];
console.log (arr) ; // [1, 2, 3]
console.log (newArr) ; // [1, 2, 3, 4]
// 객체
let user = {
name : "nbc",
age : 30,
};
let user2 = {...user}; // 풀고 다시 묶은거라 user 와 값이 같다.
// 나머지 매개변수 (rest parameter)
function exampleFunc (a, b, c, ...args) { // ..args 추가적으로 arguments 가 들어올 수 있다는 의미
console.log(a,b,c); // 1 2 3
console.log(...args) ; // 4 5 6 7
console.log(args); // [4, 5, 6, 7]
exampleFunc (1, 2, 3, 4, 5, 6, 7);
// 템플릿 리터럴 (template literal) - `` 안에 변수나 자바스크립트 문법까지 넣을 수 있다.
const testValue = "안녕하세요!";
console.log (`Hello World ${testValue}`);
console.log(`
hello
my name is Javascript!
Nice to meet you!
`);
// 등의 멀티라인 사용이 가능하다.
자바스크립트에서 함수는 일급 객체 라고 한다. 따라서 함수를 매우 유연하게 사용할 수 있다.
일급 객체(First-class Object) 란 다른 객체들이 일반적으로 적용 가능한 연산을 모두 지원하는 객체를 가리킨다.
1) 변수에 함수를 할당할 수 있다.
- 함수가 마치 값으로 취급된다.
- 함수가 나중에 사용될 수 있도록 조치가 되었다.
const sayHello = function () {
console.log("hello");
} ;
2) 함수를 인자로 다른 함수에 전달할 수가 있다.
2-1) 콜백함수 : 매개변수로써 쓰이는 함수
2-2) 고차함수 : 함수를 인자로 받거나 return 하는 함수
function callFunction(func) {
// 매개변수로 받은 변수가 사실, 함수다.
func ();
}
const sayHello = function () {
console.log("Hello!");
};
callFunction(function () {
console.log("Hello!");
});
3) 함수를 반환할 수 있다.
function createAdder(num) {
return function (x) {
return x + num;
};
}
const addFive = createAdder(5);
console.log(addFive (10)); // 15
일급객체로써의 함수 (2)
const person = {
name : "John",
age : 31
isMarried : true,
sayHello : function() {
console.log("Hello, My name is" + this.name);
//// or console.log (`Hello, My name is ${this.name}`); // Hello, My name is John
를 화살표 함수로 바꾸면
sayHello: () => {
console.log (`Hello, My name is ${this.name}`)};
},
},
}; // Hello, My name is undefined
person.sayHello();
화살표 함수는 this 를 binding 하지 않는다.
배열의 요소로 함수를 할당하는 것
const myArr = [
function (a,b) {
return a+b;
},
function (a,b) {
return a-b;
},
];
// 더하기
console.log(myArr[0](1,3)); // 4
console.log(myArr[1](10,7); // 3
function multiplyBy(num) {
return function (x) {
return x * num;
};
}
function add (x,y) {
return x+y;
}
const multiplyByTwo = multiplyBy(2);
const multiplyByThree = multiplyBy(3);
console.log(multiplyByTwo (10)); // 20
console.log(multiplyByThree (10)); // 30
const result = add ( multiplyByTwo(5), multiplyByThree(10));
console.log (`Final => ${result}`); // Final => 40
// Map
// JavaScript -> 객체, 배열 을 이용하여 많고 다양하며 복잡한 프로그램을 만들어 왔지만 현실세계를 반영하기는 어려웠다.
// Map, Set 등 추가적인 자료구조가 등장하게 되었다.
// Map, Set 의 목적 : 기존의 객체 또는 배열보다 데이터의 구성, 검색, 사용을 효율적으로 처리
1) Map
- Key / Value
- Key 에 어떤 데이터타입(유형) 도 다 들어올 수 있다.
- Map 은 키가 정렬된 순서로 저장되기 때문이다.
- 기능으로는 검색, 삭제, 제거, 여부 확인 등이 있다.
const myMap = new Map ();
// myMap.set ('key', 'value');
// myMap.get ('key') //set 과 get 은 pair
myMap.get('key')
반복하는 방법으로는 keys, values, entries 가 있다.
const myMap = new Map();
myMap.set("one",1);
myMap.set("two",2);
myMap.set("three",3);
console.log (myMap.keys()); // [Map Iterator] {'one', 'two', 'three'}
for(const key of myMap.keys()){
console.log(key);
}
console.log (myMap.values()); // [Map Iterator] {1, 2, 3}
for(const key of myMap.values()){
console.log(value);
}
console.log (myMap.entries()); // { ['one',1], ['two',2], ['three',3]}
for (const entry of myMap.entries()){
console.log(entry);
}
// ['one', 1]
['two', 2]
['three', 3]
console.log(myMap.size); // map의 사이즈(길이) // 3
console.log(myMap.has("two")); // key 기반 검색 // true
// Set
- 고유한 값을 저장하는 자료구조로 값만을 저장하고 키를 저장하지 않는다.
- 값이 중복되지 않는 유일한 요소로만 구성된다.
const mySet = new Set();
mySet.add("value1")
mySet.add("value2")
mySet.add("value2")
console.log(mySet.size); // 2
console.log(mySet.has("value1")); // true
for (const value of mySet.values()) {
console.log(value);
}