| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
- ajax
- html
- mongodb
- spring
- MySQL Error
- git
- sessionStorage
- javascript
- jsp
- Get
- Bootstrap
- spread operator
- 예매로직
- AWS RDS
- AWS
- ssh
- node.js
- topologySpreadConstraints
- mysql
- 인생이재밌다
- zombie-hit apartment
- json
- AWS Route53
- Java
- post
- Kubernetes
- 영화예매
- chartjs
- terminationGracePeriodSeconds
- ES6
- Today
- Total
jongviet
Aug 23, 2021 - JS ES6 update... 본문
*8월23일
-JavaScript 관련 업데이트
!!
피연산자를 불린 값으로 변환; 0이면 false, 1이면 true 반환
let a = 1;
let b = 0;
let c = "1";
let d = "0";
console.log(!!a);
console.log(!!b);
console.log(!!parseInt(c));
console.log(!!parseInt(d));
함수관련 스코핑
->함수 내부에서 선언된 변수는 함수 외부에서 접근 불가 // local
->함수 외부에서 선언된 global은 당연히 어디서도 접근 가능
queue 선입선출 방식
call stack 글자 그대로 쌓여서, 후입선출 방식으로 처리되는 구조
instance method //객체 안에 함수를 담은 것
static method // 클래스 안에 함수를 담은 것
super // 부모 객체 함수 호출,,,, super();
skeleton code // 하나의 프로그램이 동작하는 전체 과정을 한 눈에 알아볼 수 있도록 구조를 나타낸 틀
Pseudo code == 의사코드 // 실제 코드를 흉내낸 가짜 코드
커링 // 특정 함수에서 정의된 인자의 일부를 넣어 고정시키고, 나머지를 인자로 받는 새로운 함수를 만드는 것
array.reduce // acc, curVal, curIdx, array
->배열 전체 누적값 반환 accumulator 개념으로 보면 됨;
let newArr = [3, 3, 2, 1, 2, 3, 5];
let result6 = newArr.reduce( (acc, curVal) => acc + curVal);
console.log(result6); // 19
let newArr = [1, 2, 3, 4, 5];
let initialVal = 10;
let newObjArr = [
{x: 5}, {x: 10}, {x: 15}
]
let arr1 = [5, 3];
let arr2 = [6, 3];
let arr3 = [7, 1];
let result6 = newArr.reduce( (acc, curVal) => acc + curVal);
console.log(result6); //15
let result7 = newArr.reduce( (acc, curVal) => acc + curVal, initialVal); //초기값주면 초기값까지 더해서 반환
console.log(result7); //20
//object로 구성된 배열도 누적값 반환 가능, 다만 반드시 초기값을 주어 각 항목이 함수를 거칠 수 있도록 구성해야함
let result8 = newObjArr.reduce( (acc, curVal) => acc + curVal.x, initialVal);
console.log(result8);
//배열 병합
let result9 = [arr1, arr2, arr3].reduce( (acc, curVal) => acc.concat(curVal));
console.log(result9);
//배열 객체 내의 값 인스턴스 개수 확인
let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
let countedNames = names.reduce( (allNames, name) => {
if (name in allNames) { //allNames에 초기값 ""에서 하나씩 누적, 최종적으로 마지막 Alice는, 첫번째 Alice가 있는 상태로 들어가니, ++가 됨
console.log(1);
allNames[name]++;
}
else {
console.log(2);
allNames[name] = 1;
}
return allNames;
}, {});
console.log(countedNames);
//age속성 값으로 각 객체 분류
//Obj 속성으로 객체 분류
let people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 },
{ name : 'Ki', age: 31}
];
function groupBy(objectArray, property) {
return objectArray.reduce( (acc, obj) => {
// console.log(obj[property]);
let key = obj[property]; //배열 객체 내 각각의 obj[age] 기준 key값 21, 20;
if (!acc[key]) { //age 기준 최초에는 각 그룹 별 key값이 없어서 새로 생성
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {}); //초기값으로 빈 객체
}
let groupedPeople = groupBy(people, 'age');
console.log(groupedPeople);
//spread operator
...배열명 -> 특정 배열 복사(기존 배열 영향 x)
//여러 배열과 임의의 초기값 연결
let friends = [{
name: 'Anna',
books: ['Bible', 'Harry Potter'],
age: 21
}, {
name: 'Bob',
books: ['War and peace', 'Romeo and Juliet'],
age: 26
}, {
name: 'Alice',
books: ['The Lord of the Rings', 'The Shining'],
age: 18
}];
let allbooks = friends.reduce( (acc, curVal) => ([...acc, ...curVal.books]), ['gogo']);
console.log(allbooks);
//배열 내 중복 항목 제거
let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
let arr_word = ["hi", "hello", "hola", "chao", "hello", "hola", "chao"];
let uniqueArray = Array.from(new Set(arr)); //arr라는 배열을 set형태로 유니크하게 만든 후, array.from으로 배열화 하여 uniqueArray에 저장
console.log(uniqueArray); //[1,2,3,4,5]
let uniqueArray2 = Array.from(new Set(arr_word));
console.log(uniqueArray2);
//concat + map으로 배열 가공 후 combine
let arr_word = ["hi", "hello", "hola", "chao"];
let arr_word2 = arr_word.map( (v) => (v + "_added"));
let combinedArr = arr_word.concat(arr_word2);
console.log(combinedArr);
//slice usage : 배열 및 문자열 모두 사용 가능 slice(시작자리, 끝자리)
const nums = [1, 23, 45, 56, 64, 102];
const firstTothirdNums = nums.slice(0, 3);
console.log(firstTothirdNums); // [1,23,45]
const a = "abcdefg";
let out = a.slice(0, 3);
console.log(out); //abc
//find : 주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환
const nums = [1, 23, 45, 56, 64, 102];
let findOne = nums.find( (v) => v < 60);
console.log(findOne);
//filter : 조건 만족하는 전체 반환
const nums = [1, 23, 45, 56, 64, 102];
let findTwo = nums.filter( (v) => v >= 45);
console.log(findTwo);
call by value && call by reference //자바랑 같음;
//object 포함된 배열 전체 출력
const nums = [1, 23, 45, 56, 64, 102, {name : "ki", age : 22}];
//forIn은 배열 내 객체도 key:value 모두 출력
for(let a in nums) {
console.log(nums[a]);
}
//함수 객체 <-> boolean, number, string, null, undefined 등 기본데이터 타입 제외하고 모두 객체임;
//자바스크립트 모든 객체는 자신의 프로토타입을 가리키는 [[prototype] __proto__프로퍼티를 내부 프로퍼티로 갖는다.
->프로토타입은 해당 함수로 생성되는 모든 객체에 영향을 미침. 즉, 모든 객체의 원형이 되는 객체로 보면 됨
->
//prototype Link와 Object가 존재함
//객체는 언제나 함수로 생성됨;
function Person() {}
let personObj = new Person();
let obj = {}; // == new Object();
let one = new Member_test();
console.log(one.joined);
let two = new Member_test();
console.log(two.joined);
function Person(){}
let ki = new Person();
let park = new Person();
Person.prototype.getType = function () {
return "humannn";
}
Person.prototype.getName = function () {
return "naaaaaammmeee";
}
console.log(ki.getType());
console.log(park.getType());
console.log(park.getName());
//즉시 실행 함수 : 최초 초기화 할 시 유용할 것으로 보임, 읽힐 때 그대로 실행
(function () {
console.log("즉시실행");
})()
let a = 0;
let b = 1;
(function () {
console.log("즉시실행");
a = 10;
b = 20;
})()
console.log(a);
-class
//class도 함수의 일종; 함수를 함수 표현식 및 선언으로 정의하듯, class도 표현식 & 선언으로 정의할 수 있음
const rectangle = new Rec(); //함수 선언은 호이스팅이 일어나지만 클래스는 그렇지 않다. 래퍼런스 에러 리턴됨
class Rec {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
// unnamed
let Rectangle2 = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
// console.log(Rectangle2.name);
// 출력: "Rectangle"
// named
let Rectangle3 = class Rectangle3 {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
// console.log(Rectangle3.name);
// 출력: "Rectangle2"
-정적메소드
//정적메서드(클래스 내의 함수)와 속성
//static 키워드는 클래스를 위한 정적 메서드를 정의함. 클래스의 인스턴스화 없이 호출되며, 인스턴스에서는 호출 불가
class test {
constructor(x, y) {
this.x = x;
this.y = y;
}
static moveToLeft(x) {
x = x - 1;
return x;
}
}
let leftTest = test.moveToLeft(5);
console.log(leftTest);
-"use strict"가 함수 내에서 선언되면 해당 함수만, 함수밖에서 선언되면 전체 컨텍스트에 영향을 미침
const Animal = {
speak() {
console.log(`${this.name} makes a noise.`);
}
};
class Dog {
constructor(name) {
this.name = name;
}
}
// 이 작업을 수행하지 않으면 speak를 호출할 때 TypeError가 발생합니다
Object.setPrototypeOf(Dog.prototype, Animal);
let d = new Dog('Mitzie');
d.speak(); // Mitzie makes a noise.
-closure(함수안의 함수, 즉 내부 함수);
-내부 함수는 외부함수(바로 바깥 레이어 함수)의 변수에 접근할 수 있음;
function init() {
let name = "Mozilla"; // name은 init에 의해 생성된 지역 변수이다.
function displayName() { // displayName() 은 내부 함수이며, 클로저다.
let name = "Gozilla";
console.log(name); // 부모 함수에서 선언된 변수를 사용한다.
}
displayName();
}
init();
-클로저 스코프에는 총 3개 범위가 있음, local / outer func / global
-클로저 모듈 패턴
//변수에 받아서 사용해야지 증감 누적 및 get 가능
//각기 다른 privateCnt를 다루면서, privateCnt를 밖으로 노출시키지 않는다.
function makeCounter() {
let privateCnt = 0;
return {
increment : function() {
privateCnt++;
},
decrement : function() {
privateCnt--;
},
getValue: function() {
return privateCnt;
}
}
}
let test1 = new makeCounter();
test1.increment();
test1.increment();
test1.increment();
console.log(test1.getValue());
let test2 = new makeCounter();
test2.decrement();
test2.decrement();
test2.decrement();
test2.decrement();
console.log(test2.getValue());
-커링(currying) : 함수 하나가 n개의 인자를 받는 대신, n개의 함수를 만들어 각각 인자를 받게 하는 방법
function adder(x) {
return function(y) {
return x+y;
}
}
let test = adder(10)(5);
console.log(test);
//x에 고정값을 지정해놓고 계속해서 재사용 할 수 있음
let add100 = adder(100);
console.log(add100(2)); // 102
console.log(add100(10)); // 110
//외부 함수의 변수가 저장되어 마치 템플릿 함수와 같이 사용 가능함.
let add5 = adder(5);
console.log(add5(2));
'javascript & typescript' 카테고리의 다른 글
| Sep 5, 2021 - 자바스크립트 작동 원리 필기 (1) | 2021.09.05 |
|---|---|
| Aug 26, 2021 - JS ES6 update2 .... (0) | 2021.08.26 |
| Aug 19, 2021 - array.map, arrow function, array.filter (1) | 2021.08.19 |
| Aug 16, 2021 - Destructuring, set, weakset, map, weakmap, template (0) | 2021.08.16 |
| Aug 15, 2021 - spread operator, from, includes, arguments (1) | 2021.08.15 |