JavaScript 기초부터 배우기 - 5

donggae·2023년 9월 22일
1

JavaScript

목록 보기
5/7
post-thumbnail

1. 객체(Object)

객체는 관련된 데이터와 함수의 집합 (프로퍼티와 메소드)

다음은 객체를 생성하는 두 가지 방법이다.

객체 생성자

let user = new Obejct(); 

객체 리터럴

let user = {}; // 객체 리터럴을 사용한 빈 객체 만들기

객체 리터럴을 사용하는 방법이 일반적이고 더 간단하여 자주 사용된다.

  • 객체에는 여러가지 값들을 넣을 수 있지만, 키와 값 쌍을 넣어야 된다.
  • 키와 값을 쌍으로 가지는 것을 프로퍼티, 객체의 프로퍼티를 통해 데이터를 구조화하고 관리 할 수 있다.
  • 객체의 메서드는 객체가 가지고 있는 함수, 객체 내의 동작 또는 객체와 관련된 동작을 수행한다.

1-1. 프로퍼티(Property)와 메소드(Method)

let user = {
  name: "Hyun",
  age: 27,
  greet: function() {
      console.log("Hello, I'm " + this.name + " and I'm " + this.age + " years old.");
  },
};

user.greet(); // Hello, I'm Hyun and I'm 27 years old.
  • 콜론 :을 사용하여 키와 값을 구분한다.
  • 키에는 문자형, 값에는 모든 type이 사용된다.
  • 객체의 동작을 수행하는 메소드

1-2. 객체의 값 추가, 삭제, 변경

const user = {
	name: "Hyun",
  	age : 26,
  	blood : "B",
}

user.birth = ("97/08/22"); // 객체의 birth 값 추가하기

console.log(user.birth); // 97/08/22
console.log(user["birth"]); // 97/08/22

user.age = 27; // 객체의 age 값 변경하기

console.log(user.age); // 27
console.log(user["age"]); // 27

delete user.blood; // delete를 이용하여 객체의 blood 값 삭제하기

console.log(user.blood); // undefined
console.log(user["blood"]); // undefined

// delete를 사용하게 되면 메모리에서 지워지지 않는다. 그렇기에 다음과 같은 방법 지향

user.age = null; // null 을 이용하여 객체의 age 값 삭제하기

console.log(user.age); // null

왜 상수로 선언된 user 객체를 수정해도 에러가 발생하지 않을까?
-> 객체 내의 프로퍼티 값을 변경하는 것은 상수 객체를 변경하는 것이 아니기 때문이다.

1-3. 메소드와 This

let user = {
	name: "Hyun",
  	age : 27,
  	greet() {
    	console.log(this.name); // this -> 현재 객체를 나타낸다.
    }
};

user.greet(); // Hyun

this의 동작 방식을 알아보자

let user1 = { name: "Dong" };
let user2 = { name: "Hyun" };

function greet() {
	console.log( this.name );	
}

user1.func = greet;
user2.func = greet;

user1.func(); // Dong
user2.func(); // Hyun

이와 같이 this는 . 앞의 객체를 참조하기에 this의 값이 서로 달리즈는 것을 알 수 있다.



2. 배열(Array)

여러 개의 값을 순서대로 저장하는 데이터 구조

2-1. 배열 선언하기

const arr1 = new Array();
const arr2 = [];

대부분 두번째 방법으로 배열을 선언한다.

2-2. 배열에 접근, 수정하기

let oddNumbers = [1,3,5,7,9];
console.log( oddNumbers[0] ); // oddNumbers[N] 을 통해 N번째 요소에 접근을 할 수 있다.

oddNumbers[4] = 11;
console.log( oddNumbers[4] ); // N번째의 요소 수정하기

console.log( oddNumbers.length ); // 5 length를 통해 배열의 담긴 요소위 갯수 파악하기

console.log( oddNumbers ); // 요소 전체를 출력하기

oddNumbers.push(15);
console.log( oddNumbers[5] ); // push를 통해 배열에 새로운 요소 추가하기

2-3. 배열의 내장함수 알아보기

forEach

반복문 for문을 대체 할 수 있다.

const korea = ["서울", "대구", "부산", "경기도"];

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

위와 같은 반복문을 forEach 문으로 변경해보자

const korea = ["서울", "대구", "부산", "경기도"];

korea.forEach(city => {
	console.log(city);
});

forEach 함수의 파라미터 city는 각 원소를 가르키게 된다.


map

새로운 배열을 만들때 유용하다.

const array = [1,2,3,4,5,6,7,8,9,10];

const array2 = [];

array.forEach(el => {
	array2.push(el * 2);
})

console.log(array2);

새로운 배열을 map을 이용하여 만들어보자

const array = [1,2,3,4,5,6,7,9,10];

const array2 = array.map(n => n * 2);

console.log(array2);

변화를 주는 함수를 전달하여 새로운 배열 생성


indexOf

원하는 원소의 순서 찾기

const korea = ["서울", "대구", "부산", "경기도"];
const index = korea.indexOf("대구");

console.log(index); // 1

index의 값은 0 부터 시작하여 원소의 순서를 반환
-1이 반환 되는 경우 해당 배열에 없다는 뜻


findIndex

배열 안에 있는 값이 객체, 배열일 경우 indexOf를 사용 할 수 없어서 findIndex를 사용한다.

const korea = [
  {
    id: 1,
    city: "Seoul"
  },
  {
    id: 2,
    city: "Daegu"
  },
  {
    id: 1,
    city: "Busan"
  },
  {
    id: 1,
    city: "Ulsan"
  }
];

다음과 같이 배열에 있는 값이 객체일 경우 findIndex 를 통해 원하는 조건을 찾을 수 있다.

const korea = [
  {
    id: 1,
    city: "Seoul"
  },
  {
    id: 2,
    city: "Daegu"
  },
  {
    id: 1,
    city: "Busan"
  },
  {
    id: 1,
    city: "Ulsan"
  }
];

const index = korea.findIndex(el => el.city === "Seoul");
console.log(index); // 0

find

findIndex에서 순서가 아닌 값 자체를 반환해준다.


const korea = [
  {
    id: 1,
    city: "Seoul"
  },
  {
    id: 2,
    city: "Daegu"
  },
  {
    id: 1,
    city: "Busan"
  },
  {
    id: 1,
    city: "Ulsan"
  }
];

const index = korea.find(el => el.city === "Seoul");
console.log(index); // {id: 1, city: "Seoul"}

filter

배열에서 특정 조건을 만족하는 값들만 따로 추출하여 새로운 배열 만들기

const korea = [
  {
    id: 1,
    city: "Seoul",
    visit: true,
  },
  {
    id: 2,
    city: "Daegu",
    visit: false,
  },
  {
    id: 1,
    city: "Busan",
    visit: true,
  },
  {
    id: 1,
    city: "Ulsan",
    visit: false,
  }
];

const visitNoCity = korea.filter(el => el.visit === false);

console.log(visitNoCity); 

splice

특정 항목 제거하기

const array = [10,20,30,40,50];
const index = numbers.indexOf(30);
array.splice(index,1);
console.log(array);
  • splice(n,m) 일 때 n에서부터 m개 제거라 생각 하면 쉽고,
  • splice(n)일 때는 n번째 이후로 제거가 된다라 생각 하면 쉽다.

slice

splice랑 비슷하지만 기존 배열은 건들지 않는다.

const array = [1,2,3,4,5];
const array2 = array.slice(0,2) // 0~2 까지

console.log(array2); // [1,2]
console.log(array); // [1,2,3,4,5]

shift와 pop

배열에서 원소를 추출하기

// shift
const array = [1,2,3,4,5];
const number = array.shift();

console.log(array); // [2,3,4,5]
console.log(number); // 1
// pop
const array = [1,2,3,4,5];
const number = array.pop();

console.log(array); // [1,2,3,4]
console.log(number); // 5

shift는 배열의 첫번째 원소, pop은 배열의 마지막 원소 추출


unshift

배열의 맨 앞에 새 원소 추가하기

const array = [1,2,3,4,5];
array.unshift(0);

console.log(array);

concat

여러개의 배열을 하나의 배열로 합치기

const arr1 = [1,2,3];
const arr2 = [4,5,6];

const arr3 = arr1.concat(arr2);
console.log(arr3); // [1,2,3,4,5,6]

합쳐진 배열의 순서는 A.concat(B) 라고 하면 [A,B] 순으로 반환된다.


join

배열 안의 값들을 문자열 형태로 합치기

const array = [1,2,3,4,5];
console.log(array.join()); // 1,2,3,4,5
console.log(array.join(' ')); // 1 2 3 4 5
console.log(array.join(', ')); // 1, 2, 3, 4, 5

reduce

해당 배열의 총합을 구할 때 사용한다.

const array = [1,2,3,4,5];

let sum = 0;
array.forEach(n => {
	sum += n;
});
console.log(sum);

해당 코드를 reduce 를 이용하여 변경해보자

const array = [1,2,3,4,5];
let sum = array.reduce((cal, current) => cal + current, 0);

console.log(sum);


3. 비 구조화 할당

객체나 배열을 변수에 할당하는 것

3-1. 배열에서의 비 구조화 할당

let arr = ["one", "two", "three", "four"];

다음과 같은 배열이 있다고 생각을 해보자 배열에서의 값을 다 얻을려면 다음과 같이 값을 얻어야 한다.

console.log(arr[0]); // one
console.log(arr[1]); // two
console.log(arr[2]); // three
console.log(arr[3]); // four

하나씩 다 호출을 해야하고, 반복적인 부분이 있기에 번거로울 수 있다

let arr = ["one", "two", "three", "four"];
let [one, two, three, four] = arr;

console.log(one); // one
console.log(two); // two
console.log(three); // three
console.log(four); // four

// 위의 코드를 더 간단하게 수정해보자

let [one, two, three, four] = ["one", "two", "three", "four"];
console.log(one); // one
console.log(two); // two
console.log(three); // three
console.log(four); // four

arr 배열에서 0번째 인덱스는 one, arr 배열에서 1번째 인덱스는 two ... 이렇게
one, two, three, four에 index 0, 1, 2, 3번을 할당 한다
배열의 값을 순서대로 할당 받아 사용할 수 있다.

let [one, two, three, four, five] = ["one", "two", "three", "four"];
console.log(five) // undefined

여기서 만약 선언 되지 않는 값에 대해서 값을 넣게 되면 undefinde가 나오게 되는데
undefined가 나오면 안되는 상황이라 하면
배열에서 새로운 값에 기본 값을 설정 하면 된다.

let [one, two, three, four, five = "five"] = ["one", "two", "three", "four"];
console.log(five) // five

3-2. 배열에서 값들의 스왑(Swap)

배열 내에서 두 값을 서로 교환 하는 것

let arr = [1, 2, 3, 4];

배열 arr에서 첫번째 요소와 마지막 요소의 위치를 바꾸어 보자

let arr = [1, 2, 3, 4];

let tmp = arr[0];
arr[0] = arr[3];
arr[3] = tmp;

console.log(arr) // 4, 2, 3, 1

어떠한 방식으로 값들이 바꼈는지?
1. tmp라는 임시 변수에 arr[0]의 값을 저장
2. arr[0]arr[3]값을 넣고, arr[3]tmp값을 넣는다
3. 결론 적으로는 arr[0]arr[3] 값을 넣고, arr[3]arr[0] 값을 넣는 개념


다음은 비 구조화 할등을 사용하여 값들을 스왑 해보는 과정이다.
let arr = [1, 2, 3, 4];
[arr[0], arr[3]] = [arr[3], arr[0]];
console.log(arr); // 4, 2, 3, 1

3-3. 객체에서의 비 구조화 할당

let object = {one: "one", two: "two", three: "three", four: "four"};

다음과 같은 객체가 있다고 생각을 해보자 객체에서의 값을 새로운 변수에 할당하려면 다음과 같이 해야한다.

let one = object.one;
let two = object.two;
let three = object.three;
let four = object.four;

console.log(one, two, three, four); // one two three four

하나씩 다 호출을 해야하고, 반복적인 부분이 있기에 번거로울 수 있다
비 구조화 할당으로 코드를 조금 더 단순하게 만들어보자

let object = {one: "one", two: "two", three: "three", four: "four"};

let {one, two, three, four} = object;
console.log(one, two, three, four);

object의 키 값을 기준으로 one이라는 키를 갖는 값을 변수 one에 저장 ...
object의 키 값을 기준으로 four이라는 키를 갖는 값을 변수 four에 저장하는 방식이다.

객체에서의 비 구조화 할당은 순서가 아닌 key값을 기준으로 할당하게 된다.

객체에서의 비 구조화 할당은 키 값으로 할당을 하기에 변수가 키 값으로 강제되는 경향이 있다.
다음은 키 값으로 얻은 변수의 네이밍을 바꾸는 과정이다

let object = {korea: "서울", japan: "도쿄", usa: "워싱턴"};

let {usa, korea, japan} = object; // 배열과는 다르게 순서와 상관이 없다는 것을 볼 수 있다.
console.log(korea, japan, usa);

// 그럼 이제 키와 동일한 변수의 네이밍을 바꾸어 보자

let object = {korea: "서울", japan: "도쿄", usa: "워싱턴"};
let {usa: 미국, korea: 한국, japan: 일본} = object; // 새로운 변수에 할당하기
console.log(한국, 일본, 미국);


4. 정리하는 문제

  1. 정수 n이 매개변수로 주어질 때 n의 각 자리 숫자의 합을 return하도록 solution 함수를 완성해주세요
function solution(n) {
    var answer = 0;
    const str = n.toString();
    
    for( let i = 0; i < str.length; i++) {
        answer += parseInt(str[i])
    }
    
    return answer;
}

처음에 join해서 구간을 나눠야 했나 했는데 그게 아니였다 숫자를 문자로 변경 후
그 길이를 체크해서 각각 숫자열로 다시 변환

문자열의 길이를 이용하여 반복문을 통해 자리수 자르기

  1. 문자열 배열 strlist가 매개변수로 주어집니다. strlist 각 원소의 길이를 담은 배열을 retrun하도록 solution 함수를 완성해주세요.
function solution(strlist) {
    const answer = [];
    for(let str of strlist) {
        answer.push(str.length);
    }
    return answer;
}

이걸 풀고나면 다른 사람은 어떻게 풀었는지 볼 수 있는데 같은 문제여도 정말 다 다르다
이렇게도 풀 수 있구나라는 생각도 들더라

배열로 새로운 배열을 만들 때 map함수가 유용하게 쓰이는 것 같다 다음엔 그렇게 풀어보자

  1. 정수가 담긴 배열 array와 정수 n이 매개변수로 주어질 때, array에 n이 몇 개 있는 지를 return 하도록 solution 함수를 완성해보세요.
function solution(array, n) {
    let answer = 0;
    const array2 = array.filter(el => el === n)
    
    answer = array2.length;
    
    return answer;
}

고민 하다가 이거 filter로 하면 되겠는데? 라고 해서 했는데 처음에 error가 뜨길래 아 아닌가 했는데 fillter로 써버림,,,, 오타 잘 체크하자 그래도 공부한걸 써보니 조금 더 도움이 되었던 것 같다

  1. 영어에선 a, e, i, o, u 다섯 가지 알파벳을 모음으로 분류합니다. 문자열 my_string이 매개변수로 주어질 때 모음을 제거한 문자열을 return하도록 solution 함수를 완성해주세요.
function solution(my_string) {
    const vowels = 'aeiouAEIOU';
    let answer = '';
    
    for(let i = 0; i < my_string.length; i++) {
        const str = my_string[i];
        if(vowels.indexOf(str) === -1) {
            answer += str
        }
    }
    
    return answer
}

나름 진지하게 푼 문제인데 어떻게 풀지 하다가 indexOf를 이용해서 포함이 아니면 -1 반환 하는걸 이용해서 풀었다

  1. 선분 세 개로 삼각형을 만들기 위해서는 다음과 같은 조건을 만족해야 합니다.
    가장 긴 변의 길이는 다른 두 변의 길이의 합보다 작아야 합니다.
    삼각형의 세 변의 길이가 담긴 배열 sides이 매개변수로 주어집니다. 세 변으로 삼각형을 만들 수 있다면 1, 만들 수 없다면 2를 return하도록 solution 함수를 완성해주세요.
function solution(sides) {
    sides.sort((a, b) => a - b);
	console.log(sides);
    let [a, b, c] = sides;
    
    return a + b > c ? 1 : 2
}

이거 보자마자 비 구조화 할당 해서 변수 값 합쳐서 비교 하면 될 것 같은데
라고 생각 들어서 했는데 정답이여서 기분 좋았음 + sort() + 비교 함수 사용하기

profile
아자자자

0개의 댓글