typeof
: type을 반환 ex) typeof null -> object
Object.prototype.toString.call()
: Object의 좀 더 상세한 type을 반환 ex) Object.prototype.toString.call(Null) -> [Object null]
JavaScript 프로토타입 기반 언어
객체를 생성했을 때 그 객체에는 prototype이라는 object가 자동 생성
자세한 설명은 아래 참고...
https://medium.com/@bluesh55/javascript-prototype-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0-f8e67c286b67
==
: 값 비교. 동등 연산자. 형 변환이 발생함 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
console.log( true ? "참" : "거짓" ); // 참
console.log( false ? "참" : "거짓" ); // 거짓
// 랜덤한 숫자를 꺼내서 정수를 얻음
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와 같은 역할
}
arr = ["apple", "banana", "orange"];
for(i in arr){
alert(i); // 0, 1, 2
}
for(i of arr){
alert(i); //apple, banana, orange
}
Truthy(참 같은 값)
true, {}, [], 1, 2, 'false', -12, '3.14' ...
Falsy(거짓 같은 값)
false, '', null, undefined, 0, -0, Nan
const sumArrow = (a, b) => a + b
console.log(sumArrow(3, 4)); // 7
----------------------------------------------------
const obj = x => ({
name: 'gildong'
})
const a = 1;
const b = 3;
(function (){
console.log(a+b);
}());
or
(function (){
console.log(a+b);
})();
const a = 3;
const b = 4;
sum();
function sum(){
console.log(a+b); // 7, 호이스팅, 함수의 선언
}
const sumValue = function() {
console.log(a+b); // 오류, 함수의 표현
}
setTimeout(function() {
console.log('JIHYE0526');
}, 3000) // 3초 뒤에 실행
setTimeout(() => {
console.log('JIHYE0526');
}, 3000);
setTimeout(() => {
console.log('JIHYE0526');
}, 2000); // 2초 뒤에 실행
const timer = setTimeout(() => {
console.log('JIHYE0526');
}, 3000);
const h1El = document.querySelector('h1');
h1El.addEventListener('click', () => {
clearTimeout(); // body 클릭하면 타이머 종료
});
const timer = setInterval(()=>{
console.log('JIHYE0526');
}, 2000);
const h1El = document.querySelector('h1');
h1El.addEventListener('click', () => {
clearInterval(timer);
});
function timer(callback) { // 2. console.log를 인자로 받음
setInterval(()=>{
console.log('JIHYE0526');
callback(); // 3. 실행
}, 2000);
}
timer(() => { // 1. 실행
console.log('Done!')
})
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());
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을 사용)
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());
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);
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);
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']
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
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
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
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' // 전체 가져오기
_.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를 기준으로 중복된 값을 제거하여 unoinconst userD = _.unionBy(userA, userB, 'userId'); // userId를 고유하게 userA와 userB를 union함
_.find(collection, [predicate=_.identity], [fromIndex=0])
: 찾은 값이 들어있는 객체를 반환
_.findIndex(array, [predicate=_.identity], [fromIndex=0])
: 찾은 값이 들어있는 index를 반환
JSON.stringify()
: JavaScript 값이나 객체를 JSON 문자열로 변환JSON.parse()
: JSON 문자열의 구문을 분석하고, 그 결과에서 JavaScript 값이나 객체를 생성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
: 페이지 세션이 끝날 때 사라짐
어디선가 한번쯤 봤는데 몰랐던 내용들을 많이 알려주셔서 매우 알찼던 5주차 강의였던것 같다😊