2022.03.03 - javascript 데이터타입, switch/if문, 함수
import getType from "./getType";
// typeof : 데이터 타입 확인
console.log(typeof "hello world"); //string
console.log(typeof 123); //number
console.log(typeof true); //boolean
console.log(typeof null); //object
console.log(typeof {}); //object
console.log(typeof []); //object
console.log(getType(123)); //[object Number] -> slice(8, -1); 입력하면 number, boolean 만 남음
console.log(getType(false)); //[object boolean]
[getType ]외부 js
export default function getType(data) {
return Object.prototype.toString.call(data).slice(8, -1);
}
//특정 데이터 타입 알아내는 함수 외부 js (import로 적용 시키기)
=>import getType from "./getType";
[switch/ if문]
import random from "./getRandom";
const a = random();
switch (a) {
case 0:
console.log("a is 0");
break;
case 2:
console.log("a is 2");
break;
case 4:
console.log("a is 4");
break;
default:
console.log("rest...");
//조건에 부합하는 값이 없는경우 나머지 값
}
if (a === 0) {
console.log("a is 0");
} else if (a === 2) {
console.log("a is 2");
} else {
console.log("rest...");
}
[ 반복문 ]
//반복문 (For statement)
// for (시작조건; 종료조건; 변화조건 ){}
const ulEl = document.querySelector("ul");
for (let i = 0; i < 10; i += 1) {
const li = document.createElement("li");
li.textContent = `list-${i + 1}`;
if ((i + 1) % 2 === 0) {
li.addEventListener("click", function () {
console.log(li.textContent);
});
}
ulEl.appendChild(li);
}
변수 유효범위 : 자신이 동작할 수 있는 유효한 범위, 블럭내부{}
해당하는 변수가 유효하게 동작할 수 있는 특정 범위를 말한다.
블럭 밖에서는 동작할 수 없음.
//변수 유효범위 (Variable Scope)
// var, let, const
function scope() {
if (true) {
const a = 123;
console.log(a);
}
}
scope();
var : 함수 레벨의 유효범위를 가짐 (블록이 아님) 범위가 더 넓음
의도하지 않은 범위에서 사용하게 될 수도 있고, 메모리를 사용하게되고, 메모리 누수로 이어지기때문에
let, const를 사용해서 유효범위 내에서 동작하도록 하는것이 좋다.
[ 호이스팅 ]
호이스팅 : 함수 선언부가 유효범위 최상단으로 끌어올려지는 현상
const a = 7;
double();
function double() {
console.log(a * 2);
} // 7*2 = 14
[ 타이머 함수 ]
// setTimeout (함수,시간) : 일정 시간 후 함수 실행
// setInterval (함수, 시간) : 시간 간격마다 함수 실행
// clearTimeout() : 설정된 Timeout함수를 종료
// clearInterval() : 설정된 Interval 함수를 종료
const timer = setInterval(() => {
console.log("hyoeun!");
}, 3000);
const cH1 = document.querySelector("h1");
cH1.addEventListener("click", () => {
clearInterval(timer);
});
[ 콜백 callback ]
// 콜백 : 함수의 인수로 사용되는 함수
//setTimeout(함수,시간)
function timeout(cb) {
// (2) 그 인수가 cb라는 매개변수로 들어간다. 하나의 아직 호출되지 않은 함수임.
// (3) 그 함수를 내가 실행되길 원하는 장소에 ()를 이용하여 실행시킨다.
setTimeout(() => {
console.log("hyoeun!");
cb(); //(3)
}, 3000);
}
timeout(() => {
console.log("Done!!");
});
// (1) timeout 함수를 호출할때 하나의 익명함수를 인수로 사용했고,
[ 프로토 타입 ]
function user(first, last) {
this.firstName = first;
this.lastName = last;
}
user.prototype.getFullName = function () {
return `${this.firstName} ${this.lastName}`;
};
// new : 생성자 함수(하나의 객체 데이터가 생성되는 것 )
const hyoeun = new user("hyoeun", "kim");
const amy = new user("Amy", "Clark");
const neo = new user("Neo", "Smith");
console.log(hyoeun.getFullName());
console.log(amy.getFullName());
console.log(neo.getFullName());
* prototype을 사용해서 new라는 키워드와 함께 생성자 함수로 인스턴스를 만들어내는 개념을
자바스크립트의 클래스라고 말한다.
-> prototype 좀 더 간결하게 사용하기.
class User {
//내부함수 constructor
constructor(first, last) {
this.firstName = first;
this.lastName = last;
}
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
}
[ JS / class ]
class Vehicle {
constructor(name, wheel) {
this.name = name;
this.wheel = wheel;
}
}
const myVehicle = new Vehicle("운송수단", 2);
console.log(myVehicle);
class Bicycle extends Vehicle {
constructor(name, wheel) {
super(name, wheel);
// super = Vehicle
}
}
const myBicycle = new Bicycle("삼천리", 2);
const daughtersBicycle = new Bicycle("세발", 3);
console.log(myBicycle);
console.log(daughtersBicycle);
class Car extends Vehicle {
constructor(name, wheel, license) {
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 str = "hyohyo123@naver.com";
console.log(str.match(/.+(?=@)/)[0]);
==> hyohyo123
[숫자형/수학]
const pi = 3.14159265358979;
console.log(pi);
const str = pi.toFixed(2);
//toFixed() : 인수의 몇 번째 자리까지 유지할 것인지 설정 : 3.14
console.log(str);
console.log(typeof str); //데이터 타입 확인 : String
// 전역함수
const integer = parseInt(str); // 숫자가 들어있는 문자 데이터를 넣게되면 숫자만 추출해서 정수로 반환된다. : 3
const float = parseFloat(str); // 소숫점 자리까지 유지하면서 정수로 반환 : 3.14
console.log(integer);
console.log(float);
console.log(typeof integer, typeof float); // number, number
[ 수학함수 ]
console.log("abs:", Math.abs(-12));
// abs : 음수의 값을 절대값으로 반환
console.log("min:", Math.min(2, 8));
// min : 두 인수 중 더 작은 값
console.log("max:", Math.max(2, 8));
// max : 두 인수 중 더 큰 값
console.log("ceil:", Math.ceil(3.14));
// ceil : 올림
console.log("floor:", Math.floor(3.14));
// floor : 내림
console.log("round:", Math.round(3.5));
// round : 반올림
console.log("random:", Math.random());