function printHello(){
console.log('hello')
}
printHello();
function log(message){
console.log(message);
}
log('Hello')
log(12345)
function log(message : string) : number
함수 / / 타입 / 리턴
function changeName(obj){
obj.name = 'coder';
}
const ellie = {name : 'ellie'};
changeName(ellie);
console.log(ellie)
>>>{ name: 'coder' }
// object는 ref로 메모리에 저장되어 위의 함수에서 name이 메모리에 적용된 것
function printAll(...args){
for (let i = 0; i<args.length; i++){
console.log(args[i]);
}
}
printAll('dream','coding', 'ellie')
>>>
'dream'
'coding'
'ellie'
for (const arg of args){
console.log(arg)
}
밖에서는 안이 보이지 않고 안에서만 밖을 볼 수 있다.
function randomQuiz(answer, printYes, printNo){
if (answer === 'love you'){
printYes();
} else {
printNo();
}
}
const printYes = function() {
console.log('yes!')
};
const printNo = function() {
console.log('No!')
}
randomQuiz('wrong', printYes, printNo);
randomQuiz('love you', printYes, printNo);
>>> No! / Yes!
여기서 리커젼 일어나면 콜백 헬 일어날 수 있음. 관련한 내용은 추후 콜백 관련한 강의 들으며 복습하기
function() {} -> "() =>"
const add = function (a,b) {
return a+ b};
-> const add = (a, b) => a + b;
(function hello() {
console.log('IIFE')
})();
(괄호와 괄호)
class Person{
constructor(name, age){
// 생성자
this.name = name;
this.age = age;
}
// 메서드
speak(){
console.log(`${this.name}: hello`)
}
}
const ellie = new Person('ellie', 20)
console.log(ellie.name, ellie.age)
ellie.speak();
python class와 거의.. 진짜 똑같을 정도로 유사함.(instance 만드는 것 까지 유사)
class User{
constructor(firstName, lastName, age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get age(){
return this.age;
}
set age(value){
this.age = value;
}
}
const user1 = new User('Steve', 'Job', '-1');
console.log(user1.age);
이렇게 할 경우??
"RangeError: Maximum call stack size exceeded" : 무한 반복이 일어남
<최종 수정>
class User{
constructor(firstName, lastName, age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get age(){
return this._age;
}
set age(value){
if (value < 0){
throw Error('age can not be negative')
}
this._age = value;
}
}
const user1 = new User('Steve', 'Job', '-1');
console.log(user1.age);
class Shape {
constructor(width, height, color){
this.width = width;
this.height = height;
this.color = color;
}
draw(){
console.log(`drawing ${this.color} color of`);
}
getArea() {
return this.width * this.height;
}
}
// 상속 받는 클래스
class Rectangle extends Shape {}
const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw()
class Rectangle extends Shape {}
class Triangle extends Shape {
getArea() {
return this.width * this.height / 2;
}}
const rectangle = new Rectangle(20, 20, 'blue');
rectangle.getArea()
const triangle = new Triangle(20, 20, 'red');
triangle.getArea() {
return (this.width * this.height) / 2}
console.log(rectangle instanceof Rectangle);
약간 json 데이터 받을 때 뭐 받을지 몰라서 [] 쓰는 파이썬과 유사한 듯
console.log('name' in ellie)
for (key in ellie){
console.log(key)
}
; key 출력
for (value of array){
console.log(key)
}
; value 출력
const user4 = {}
Object.assign(user4, user);
console.log(user4);
동적 타입... 한 바구니 안에 다양한 데이터가 담길 수는 있으나.. 지양
const arr1 = new Array
or [1, 2]
그 외 방식은 Python과 유사
foreach 등 조금 다른 방식
배열 안에 들어있는 밸류들 마다 내가 전달한 함수들을 출력한다.
push, unshift, pop, shift... (저번 정리 확인)
shift, unshift : data 처리 속도 자체가 늦는다.(data 위치 때문에)
splice : 시작 인덱스~ 몇 개나 지울건지?, 지우고 새로운거 추가도 가능)
concat(배열) = 배열 합하기
indexOf('내용') : 몇 번째?(없으면 -1 ; 약간 파이썬 find 느낌)
include('내용') : 있는지?
파이썬 배열 공부할 때도 그랬지만 구글링하면서 필요할 때마다 찾아쓰면서 익숙해지는 것도 좋을 것 같다.
파이썬과 비슷한 점, 차이점 생각하며 보기
const fruits = ['banana', 'apple', 'orange'];
const result = fruits.join()
console.log(result);
>>>'banana,apple,orange'
const fruits = 'banana,apple,orange';
const result = fruits.split(',');
console.log(result)
파이썬하고 약간 개념이 다름.
array.find(function (student)=>return student.score === 90;)
// 순차적으로 호출될 때 90점인 학생 리턴
const result = students.map((student)=> student.score)
// 원래 객체인데 점수만 있는 배열 만들기
const result = students.some((student)=> student.score < 50)
// 한 사람이라도 50점 미만안거 있나?
const result = students.reduce((prev, curr) => prev + curr.score, 0)
console.log(result / student.length -1)
average 등 더 쉬운 방법은 없을까?