Notice
Recent Posts
Recent Comments
«   2025/07   »
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
Today
Total
관리 메뉴

IT CUBE

[JavaScript] 자바스크립트 기본 Part 2 본문

Front-End

[JavaScript] 자바스크립트 기본 Part 2

CUBE 2021. 10. 4. 01:34

 

 

 

함수에 object로 전달

간단하게 파라미터로 전달할 수 있음

object는 key와 value의 집합체

function print(person){
    console.log(person.name);
    console.log(person.age);
}

const soo={name:'sooing',age:20};

print(soo);

 

object 요소 추가와 삭제

soo.hasJob=true;
console.log(soo.hasJob); // true 출력

delete soo.hasJob;
console.log(soo.hasJob); // undefined 출력

 

object 받아오는 방법

console.log(soo.name);
console.log(soo['name']); // string 타입으로 지정해서 받아오기

function printValue(obj, key){
    console.log(obj[key]); // 정상 출력
    console.log(obj.key); // undefined 출력 key라는 property가 존재하지 않기 때문
}
printValue(soo,'name');

 

constructor function

반복되는 상황을 줄이기 위해 함수 하나로 줄여주는데 클래스 형태로 함수를 만들어주는 것

// object 함수로 만드는 일반적인 방법
function makePerson(name,age){
    return{
        name,
        age
    };
}
const person2=makePerson('soo',21);
console.log(person2);

// Constructor function
function Person(name,age){
    this.name=name;
    this.age=age;
}
const person3=new Person('ace',23);
console.log(person3);

 

in operator

object안에 value값이 존재하는지 확인하는 방법

console.log('name' in soo);
// true 출력

 

for.. in vs for.. of

// for.. in
for(const key in soo){
    console.log(key);
}
// name age 출력

//for.. of
const array=[1,2,4,5];
for(const value of array){
    console.log(value);
}
// 1 2 4 5 출력

 

console.clear()

이전까지 콘솔에 찍었던 것들을 비워주는 역할

 

cloning

const user={name:'soo',age:20};
const user2=user; 
user2.name='code';
console.log(user); // {name: 'code', age:20} 출력
// 같은 object를 참조하기 때문에 둘 다 바뀝니다.

// old way
const user3={};
for(const key in user){
    user3[key]=user[key];
}
console.log(user3); // {name: 'code', age: 20} 출력

// new way
const user4={};
Object.assign(user4,user);
// const user4=Object.assign({},user); (이렇게 한번에 작성할 수도 있습니다.)
console.log(user4); // {name: 'code', age: 20} 출력

//another example
const fruit1={color:'red'};
const fruit2={color:'blue',size:'big'};
const mixed=Object.assign({},fruit1,fruit2);
console.log(mixed.color+' '+mixed.size);
// 뒤에있는 것으로 계속해서 덮어씌워집니다.
// 만약 black의 fruit3이 뒤에 더 붙는다면 color는 black으로 덮어씌워집니다.
// blue big 출력

 

배열

// 배열 선언
const arr=[1,2];

for(let i=0;i<arr.length;i++){
    console.log(arr[i]);
}

// for문 사용해서 출력
for(let num of arr){
    console.log(num);
}

// forEach 사용
arr.forEach(function(arr,index,array){
    console.log(arr,index,array);
})
// arr값과 index 배열을 출력합니다.

arr.forEach((arr)=>console.log(arr)); // arr 값 출력

 

배열의 추가, 삭제, 복사

//뒤에 넣기
arr.push(3);
console.log(arr);

//뒤에서 빼기
arr.pop();
console.log(arr);

//앞에서 넣기
arr.unshift(3);
console.log(arr);

//앞에서 빼기
arr.shift();
console.log(arr);

//shift와 ushift는 push와 pop보다 느리다

//여러 데이터 넣기
arr.push(3,4,5);
console.log(arr);

//지정된 인덱스에서 지우기
arr.splice(1,2);
console.log(arr); // [1,4,5] 출력
arr.splice(1,1,6,7); 
console.log(arr); // [1,6,7,5] 출력 (지운다음에 넣기)

// 복사
const arr2=[8,9];
const newArr=arr.concat(arr2);
console.log(newArr);

 

검색

const arr = [1,6,7,5]

console.log(arr.indexOf(1)); //0 출력 (만약 없으면 -1 출력)
console.log(arr.includes(5)); //true 출력 (없다면 false 출력)

//같은 값 중에 가장 마지막 index에 있는 것을 찾기
arr.push(1);
console.log(arr); // [1,6,7,5,1] 출력
console.log(arr.lastIndexOf(1)); // 4 출력

 

유용한 함수 APIs

1. 배열을 string으로 변환하기

const fruits=['apple','banana','orange'];
const result=fruits.join(); //join 안에는 구분자를 넣어도 됨 ex.('-')
console.log(result); // apple,banana,orange 출력

 

2. string을 배열로 변환하기

const fruits='1,2,3,4';
const result=fruits.split(',');
console.log(result);

 

3. 배열 거꾸로 하기

const array=[1,2,3,4,5];
const result=array.reverse();
console.log(array);
console.log(result); 
// 둘다 reverse 적용이 된다.

 

4. 몇 가지 요소를 제거하고 새로운 배열 만들기

const array=[1,2,3,4,5];
const result=array.slice(3,5);
console.log(result); // [4,5] 출력
console.log(array); //기존 array는 그대로

 

5. 90점인 학생 찾기

class Student {
constructor(name,age,enrolled,score){
    this.name=name;
    this.age=age;
    this.enrolled=enrolled;
    this.score=score;
}
}
const students=[
    new Student('A',29,true,45),
    new Student('B',28,false,90)
];
{
const result=students.find((student)=>student.score===90
    //true가 되면 find가 종료됨
);
console.log(result);
}

 

6. 수업에 등록된 학생들만 찾아서 배열로 만들기

const result=students.filter((student)=> student.enrolled);
console.log(result);

 

7. 점수만 들어있는 새로운 배열 만들기

const result= students.map((student)=>student.score);
console.log(result);

 

8. 점수가 50점보다 낮은 학생이 있는지 확인하기

const result1=students.some((student)=>student.score<50);
console.log(result1); // true인 학생이 있는지

const result2=students.every((student)=>student.score<50);
console.log(result2); // 모든 학생이 true인지

 

9. 학생들의 평균 점수 구하기

const result=students.reduce((prev,curr)=>prev+ curr.score,0);
console.log(result/students.length);
//reduceRight은 배열을 거꾸로 돌면서 확인하는 것

 

10. 학생들의 모든 점수를 string으로 변환하기

const result=students.map((student)=>student.score).join(); //map과 join 섞기
console.log(result);

 

11. map, filter, join 함께 쓰기

const result=students.map((student)=>student.score).filter((score)=>score>50).join();
// 50점이 넘는 점수만 출력하도록 필터 추가
console.log(result);

 

12. 학생들의 점수를 정렬하고 string으로 변환하기

const result= students.map((student)=>student.score).sort((a,b)=>a-b).join();
console.log(result); // 작은 숫자부터 정렬

const result= students.map((student)=>student.score).sort((a,b)=>b-a).join();
console.log(result); // 큰 숫자부터 정렬