[패스트캠퍼스] K-디지털 기초역량훈련 - React & Redux로 시작하는 웹 프로그래밍 학습일지 5주차(react 강의)

JIHYE·2022년 5월 30일
0
post-thumbnail

1. JavaScript 심화

1.1 데이터 타입 확인

1.2 연산자

1.2.1 비교 연산자

  • == : 값 비교. 동등 연산자. 형 변환이 발생함 ex) 1 == "1" // true
  • === : 값과 타입이 같은지 비교 ex) 1 == "1" // false
    !== : 값과 타입을 비교하여 true, false로 반환

    const a = 1 === 1;
    const b = 'AB' === 'AB'

    console.log(a); // true
    console.log(b); // true

1.2.2. 삼항 연산자

console.log( true ? "참" : "거짓" ); // 참
console.log( false ? "참" : "거짓" ); // 거짓

1.3 조건문, 반복문

1.3.1 Switch

// 랜덤한 숫자를 꺼내서 정수를 얻음
const a = Math.floor(Math.random() * 10);

switch (a) {
	case 0: 
      console.log("a is 0");
      break;
    case 1: 
      console.log("a is 1");
      break;
    case 2: 
      console.log("a is 2");
      break;
    default: break; //else와 같은 역할
}

1.3.2 반복문

arr = ["apple", "banana", "orange"];

for(i in arr){
  alert(i); // 0, 1, 2
}

for(i of arr){
	alert(i); //apple, banana, orange
}

1.4 형 변환

  • Truthy(참 같은 값)
    true, {}, [], 1, 2, 'false', -12, '3.14' ...

  • Falsy(거짓 같은 값)
    false, '', null, undefined, 0, -0, Nan

1.5 함수

1.5.1 화살표 함수

  • 축약 가능
const sumArrow = (a, b) => a + b 

console.log(sumArrow(3, 4));  // 7
----------------------------------------------------
const obj = x => ({
	name: 'gildong'
})

1.5.2 즉시 실행 함수(IIFE, Immediately-Invoked Function Expression)

const a = 1;
const b = 3;

(function (){
	console.log(a+b);
}());

or

(function (){
	console.log(a+b);
})();

1.5.3 호이스팅

  • 함수 선언부가 유효범위 최상단으로 끌어올려지는 현상
const a = 3;
const b = 4;

sum();

function sum(){
	console.log(a+b);	// 7, 호이스팅, 함수의 선언
}

const sumValue = function() {
	console.log(a+b);	// 오류, 함수의 표현
}

1.5.4 타이머 함수

1.5.4.1 setTimeout

  • setTimeout(함수, 시간) : 일정 시간 후 함수 실행
setTimeout(function() {
	console.log('JIHYE0526');
}, 3000) // 3초 뒤에 실행

setTimeout(() => {
	console.log('JIHYE0526');
}, 3000);

1.5.4.2 setInterval

  • setInterval(함수, 시간) : 시간 간격마다 함수 실행
setTimeout(() => {
	console.log('JIHYE0526');
}, 2000); // 2초 뒤에 실행

1.5.4.3 clearTimeout

  • clearTimeout() : 설정된 Timeout 함수를 종료
const timer = setTimeout(() => {
	console.log('JIHYE0526');
}, 3000);

const h1El = document.querySelector('h1');
h1El.addEventListener('click', () => {
	clearTimeout(); // body 클릭하면 타이머 종료
});

1.5.4.4 clearInterval

  • clearInterval() : 설정된 Interval 함수를 종료
const timer = setInterval(()=>{
	console.log('JIHYE0526');
}, 2000);

const h1El = document.querySelector('h1');
h1El.addEventListener('click', () => {
	clearInterval(timer);
});

1.5.5 callback 함수

  • 함수의 인수로 사용되는 함수
  • 실행 위치를 보장
function timer(callback) { // 2. console.log를 인자로 받음
  setInterval(()=>{
    console.log('JIHYE0526');
    callback(); // 3. 실행
  }, 2000);
} 

timer(() => { // 1. 실행
  console.log('Done!')
})

1.5.6 생성자 함수

  • new 키워드를 사용하여 객체를 생성
  • 대문자로 시작
  • this는 메소드가 소속되어있는 객체 데이터를 말함
  • 리터럴 방식 : 특정한 방식을 거치지 않고 기호를 통해 만들어 내는 방식 ex) const person = {};
function Person(first, last) {
	this.firstName = first;
    this.lastName = last;
}
Person.prototype.getFullName = function () {
	return `${this.firstName} ${this.lastName}`
} // 공통적인것들은 따로 묶어 메모리를 효율적으로 사용 가능함??

//생성자 함수를 통해 결과를 반환한 변수 p1, p2을 인스턴스라고 함
const p1 = new Person('Gildong', 'Hong'); 
const p2 = new Person('Gildong', 'Kim');

console.log(p1);
console.log(p2.getFullName());

1.5.7 this

  • 일반(Normal) 함수는 호출 위치에서 따라 this 정의
  • 화살표(Arrow) 함수는 자신이 선언된 함수 범위에서 this 정의
const person = {
	name = 'Gildong',
    normal: function() { //ES6에서는 normal() {} 로 축약해서 사용가능
    	console.log(this.name) 
    },
    arrow: () => { console.log(this.name) }
} 

person.normal();	//Gildong
person.arrow();		//undefined

const hong = {
	name = 'Hong',
    normal: person.normal,
    arrow: person.arrow
}

hong.normal();	//Hong
hong.arrow(); 	//undefined
----------------------------------------------------------
function Person(name) {
	this.name = name;
}

Person.prototype.noraml = function () {
	console.log(this.name);
}

Person.prototype.arrow = () => {
	console.log(this.name)
}

const gildong = new Person('gildong');

gildong.normal();	//gildong
gildong.arrow();	//undefined
----------------------------------------------------------
const timer = {
	name = 'gildong',
    timeout: function(){
    	setTimeout(() = function (){
        	console.log(this.name);		
        }, 2000)
    }
}

time.timeout();	//undefined. console.log의 callback이 setTimeout 함수인데 이 함수에 name이 없기 때문
----------------------------------------------------------
const timer = {
	name = 'gildong',
    timeout: function(){
    	setTimeout(() => {
        	console.log(this.name);		
        }, 2000)
    }
}

time.timeout();	//gildong, setTimeout이 선언된 범위(timeout)에서 this 정의(일반함수 timeout은 timer의 name을 사용)

1.6 Class

class Person {
	constructor(first, last){ //constructor: function(first, last){ 과 동일
    	this.firstName = first;
        this.lastName = last;
    }
    
    getFullName() {
    	return `${this.firstName} ${this.lastName}`
    }
}

const p1 = new Person('Gildong', 'Hong'); 
const p2 = new Person('Gildong', 'Kim');

console.log(p1);
console.log(p2.getFullName());

1.6.1 상속

class Vehicle {
	constructor(name, wheel){
    	this.name = name;
        this.wheel = wheel;
    }
}

const myVehicle = new Vehicle('운송수단', 2);
console.log(myVehicle);

class Bicycle extends Vehicle { //extends는 상속을 의미
	constructor(name, wheel){
    	super(name, wheel); //부모
    }
}

const myBicycle = new Bicycle('삼천리' ,2);
const daughtersBicycle = new Bicycle('세발자전거', 3);
console.log(myBicycle);
console.log(daughtersBicycle);

class Car extends Vehicle {
	constructor(name, wheel, license) { //extends는 상속을 의미
    	super(name, wheel);
        this.license = license;
    }
}

const myCar = new Car('벤츠', 4, true);
const daughtersCar = new Car('포르쉐', 4, false);
console.log(myCar);
console.log(daughtersCar);

2. JS 데이터

  • assign 메소드는 Object에 prototype으로 만들어진 메소드가 아니기 때문에 실제 객체 데이터에는 사용이 불가능

2.1 구조 분해 할당 (Destructuring assignment)

const user = {
	name : 'Gildong',
    age : 100,
    email : 'gildong@naver.com'
}

// addr의 기본값은 Korea, 객체에 addr값이 있으면 기본값은 무시됨
// 꺼내올때는 user의 name을 꺼내오지만 사용할때는 gildong이라는 이름으로 사용하고 싶으면 :을 사용
const { name: gildong, age, email, addr = 'Korea' } = user

console.log(`이름은 ${gildong}입니다.`);

const fruits = ['Apple', 'Orange', 'Cherry'];

// a값을 사용하지 않으면 지우고 ,를 남겨두어야 함
const [, b, c, d] = fruits;

console.log(b, c, d); 

2.2 전개 연산자 (Spread)

const fruits = ['Apple', 'Orange', 'Cherry'];
console.log(...fruits); // Apple Orange Cherry

function toObject(a, b, c) {
	return {
    	a:a,
        b:b,
        c:c
    }
}

console.log(toObject(...fruits)); // {a: 'Apple', b: 'Orange', c: 'Cherry'}

---------------------------------------------------------------------------------
const fruits2 = ['Apple', 'Orange', 'Cherry', 'Banana'];

function toObject2(a, b, ...c) { // 속성과 변수명이 같으면 생략 가능
	return {
    	a:a,
        b:b,
        c:c
    }
} 
--> const toObject2 = (a, b, ...c) => ({ a, b, c }) // 화살표 연산자는 객체를 반환하기 위해서는 ()안에 작성해야 함

console.log(toObject2(...fruits)); // {a: 'Apple', b: 'Orange', c: Array(2)} // a: "Apple"b: "Orange"c: (2) ['Cherry', 'Banana']

2.3 불변성

  • 원시 데이터 : String, Number, Boolean, undefined, null
  • 참조형 데이터 : Object, Array, Function
  • 원시 데이터는 값이 같으면 데이터를 새롭게 만드는것이 아니고 메모리에 있는 값을 사용 --> 불변성
  • 참조형 데이터는 불변성이 없음?
let a = { k : 1};
let b = { k : 1};
console.log(a === b); // false

a.k = 7;
b = a;
console.log(a === b); // true

a.k = 2;
console.log(a.k, b.k) // 2 2

2.4 복사

2.4.1 얕은 복사(Shallow copy)

const user = {
	name : 'Gildong',
    age : 100,
    emails : ['gildong@naver.com']
}

const copyUser = Object.assign({}, user);
const copyUser1 = {...user};
console.log(copyUser === user) // false
console.log(copyUser1 === user) // false

2.4.2 깊은 복사(Deep copy)

user.emails.push('test@naver.com');
console.log(user.emails === copyUser.emails); // true
--------------------------------------------------------------
const user = {
	name : 'Gildong',
    age : 100,
    emails : ['gildong@naver.com']
}

const copyUser = _.cloneDeep(user); // lodash를 사용한 깊은 복사

user.age = 22;
user.emails.push('test@gmail.com');

console.log(user.emails === copyUser.emails); // false

2.5 가져오기, 내보내기

  • default export : 함수명 지정하지 않아도 되며 import 할 때 이름을 지정하면 됨. 1개만 가능
  • named export : import할 때 이름을 {} 사이에 지정된 이름을 넣어야함
export default function (data) {
	return Object.prototype.toString.call(data);
}

import checkType from './getType'
-----------------------------------------------------------------
export function checkType (data) {
	return Object.prototype.toString.call(data);
}

import { checkType as getType } from './getType'
import * as T from './getType' // 전체 가져오기

2.6 lodash

  • _.uniq(array, [iteratee=_.identity]) : identity를 기준으로 중복된 값을 제거
import _ from 'lodash'

const userA = [ {userId : '1', name : 'A'}, {userId : '2', name : 'B'} ];
const userB = [ {userId : '1', name : 'A'}, {userId : '3', name : 'C'} ];

const userC = userA.concat(userB); // 중복 존재
console.log(_.uniqBy(userC, 'userId')); // userId가 중복되면 1개로만 출력
  • _.unionBy([arrays], [iteratee=_.identity]) : identity를 기준으로 중복된 값을 제거하여 unoin
const userD = _.unionBy(userA, userB, 'userId'); // userId를 고유하게 userA와 userB를 union함
  • _.find(collection, [predicate=_.identity], [fromIndex=0]) : 찾은 값이 들어있는 객체를 반환

  • _.findIndex(array, [predicate=_.identity], [fromIndex=0]) : 찾은 값이 들어있는 index를 반환

2.7 JSON

  • JSON은 하나의 문자 데이터
  • 해석하는 과정에서 객체 데이터인것처럼 보여짐
  • 속성의 이름도 ""로 묶어야 함
  • JSON.stringify() : JavaScript 값이나 객체를 JSON 문자열로 변환
  • JSON.parse() : JSON 문자열의 구문을 분석하고, 그 결과에서 JavaScript 값이나 객체를 생성

2.8 Storage

  • localStorage : 데이터 만료되지 않음
localStorage.setItem("user", JSON.stringify(user)); // 문자 데이터로 저장하는 것을 권고

const str = localStorage.getItem("user")';
const obj = JSON.parse(str);
obj.age = 100; // 데이터 수정
console.log(obj);
localStorage.setItem("user", JSON.stringify(obj)); // 다시 저장

localStorage.removeItem("user");
  • sessionStorage : 페이지 세션이 끝날 때 사라짐

2.9 OMDb

  • Query String : 검색 문자
    ex) 주소?속성=값&속성=값




어디선가 한번쯤 봤는데 몰랐던 내용들을 많이 알려주셔서 매우 알찼던 5주차 강의였던것 같다😊

0개의 댓글