Notice
Recent Posts
Recent Comments
Link
«   2024/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
Tags
more
Archives
Today
Total
관리 메뉴

훈돌라

4.22 자바 스크립트랑 맞짱 뜨고싶은 하루 본문

카테고리 없음

4.22 자바 스크립트랑 맞짱 뜨고싶은 하루

훈돌라 2024. 4. 22. 21:35

변수, 상수

(나는 코드 스니펫에 의존하지 않는다. 직접 내가 타이핑한 vs code 임을 알린다.)

// 변수, 상수
// 메모리에 저장한다. 읽어들여서 재사용한다. = 변수

//  [변수의 5가지 주요 개념]
// 변수 이름 : 저장된 값의 고유 이름
// 변수 값 : 변수에 저장된 값
// 변수 할당 : 변수에 값을 저장하는 행위
// 변수 선언 : 변수를 사용하기 위해 컴퓨터에 알리는 행위
// 변수 창조 : 변수에 할당된 값을 읽어오는 것

// 변수를 선언할 수 있는 3가지 방법 : var, let, const
//1. var
var myVar = "Hello World";
var myVar = "Test1";
myVar = "GoodBye";
console.log(myVar);

//2. let
let myLet = "Hello World1";
//let myLet = "Test2";
myLet = "GoodBye 1";
console.log(myLet);

//3. const
const myConst = "Hello World2";
//const myConst = "Test3";
myConst = "GoodBye 2";
console.log(myConst);

// 차이점 : var 는 같은 변수로 다시 선언 할 수 있다. let, const 는 X

// var, let 은 재할당을 할 순 있지만 const 키워드로 할당하게 되면 재할당 X

 

아주 EZ 한 변수와 상수.

 

단! var let const 의 차이점은 

var 는 같은 변수로 다시 선언할 수 있다.

 

var, let 은 재할당을 할 순 있지만 const 키워드는 X

 

 

 

데이터 타입


//데이터 타입
//runtime : run 하는 타임
//코드를 작성할 때가 아니라, 실제 코드가 실행될 때
//터미널에 코드가 실행될 때
//그 때 데이터 타입이 결정된다
//Java : String a = "abc";
//const a = "abc";

// 1. 숫자 타입
// 1-1 정수
let num1 = 10;
console.log(num1);
console.log(typeof num1);

// 1-2 실수 (float)
let num2 = 3.14;
console.log(num2);
console.log(typeof num2);

// 1-3 지수형(Exp)
let num3 = 2.5e5; // 2.5 x 10^5
console.log(num3);
console.log(typeof num3);

// 1-4
// NaN : Not a Number
let num4 = "Hello" / 2;
console.log(num4);

// 1-5 infinity(무한대)
let num5 = 1 / 0;
console.log(num5);
console.log(typeof num5);

// 1-6 infinity(무한대)
let num6 = -1 / 0;
console.log(num6);
console.log(typeof num6);

 

너무 너무 이해하기 쉽다. 아직까진  강의가 아쭈 쏙 쏙 귀에 들어온다!

 

 

 

문자열 String

// 2. 문자 : String (문자열 = 문자의 나열)
// '' = ""
let str = "Hello World!";
// console.log(str);
// console.log(typeof str);

// 2-1. 문자열 길이 확인하기
// console.log(str.length);

// 2-2. 문자열 결합하기
let str1 = "Hello, ";
let str2 = "World!";
let result = str1.concat(str2);
// console.log(result);

// 2-3 문자열 자르기
let str3 ="Hello, World!";
// console.log(str3.substr(7, 5)); // 7부터 5개까지만 출력해줘
// console.log(str3.slice(7, 12)); // 7부터 12까지 출력해줘

// 2-4 문자열 검색
let str4 = "Hello, World!";
// console.log(str4.search("World"));

// 2-5. 문자열 대체
let str5 = "Hello, World!"
let result01 = str5.replace("World", "Javascript");
// console.log(result01);

// 2-6. 문자열 분할
let str6 = "apple, banana, kiwi";
let result02 = str6.split(",");
console.log(result02);

 

처음 보는 요소들이 많아져서 점점 당황스럽다.

 

 

불리언, array (배열)

// 불리언 (Boolean
// true(참), False(거짓)
let bool1 = true;
let bool2 = false;

// console.log(bool1);
// console.log(typeof bool1);
// console.log(bool2);
// console.log(typeof bool2);

// undefined
// un : not , defined : 정의하다 , 정의되지 않은 값
let x;
// console.log(x);

// null = 값이 존재하지 않음을 '명시적' 으로 나타내는 방법
let y = null;
// console.log(y);

// object (객체) : key-value pair
let person = {
    name : "kim",
    age: 28,
    test : true
};

console.log(typeof person);

// array (배열)
// 여러 개의 데이터를 순서대로 저장하는 데이터 타입
let number = [1, 2, 3, 4, 5];
let fruits = ['apple', 'banana', 'orange'];

 

불리언~ true (참) False (거짓) !

undefined 정의되지 않은 값!

 

형 변환

// 형 변환
// 형태 -> 바꾼다
// 명시적 형 변환 (개발자가 의도함), 암시적 형 변환(개발자가 의도하지 않음)

// 1. 암시적
// 1-1 문자열
let result1 = 1 + "2";
// console.log(result1);
// console.log(typeof result1);

let result2 = "1" + true;
// console.log(result2);
// console.log(typeof result2)

// {} null undefined + "1" => 문자열 (문자열과 다른 데이터 타입이 만나면 문자열이 우선 시 된다.)

// 1-2 숫자 (더하기 연산자를 제외한 다른 연산자는 숫자를 우선 시 한다.)
let result3 = 1 - "2";
// console.log(result3);
// console.log(typeof result3);

let result4 = "2" * "3";
// console.log(result4);
// console.log(typeof result4);

// 2.명시적 형 변환
// 2-1 Boolean
// console.log(Boolean(0));
// console.log(Boolean(""));
// console.log(Boolean(null));
// console.log(Boolean(undefined));
// console.log(Boolean(NaN));
// console.log("------------------");
// console.log(Boolean("false"));
// console.log(Boolean({}));

// 2-2 문자열
// let result5 = String(123);
// console.log(typeof result5);
// console.log(result5);

// let result6 = String(true);
// console.log(typeof result6);
// console.log(result6);

// let result7 = String(false);
// console.log(typeof result7);
// console.log(result7);

// let result8 = String(null);
// console.log(typeof result8);
// console.log(result8);

// let result9 = String(undefined);
// console.log(typeof result9);
// console.log(result9);

// 1-3 number.
let result10 = Number("123");
console.log(result10);
console.log(typeof result10);

 

연산자

// 연산자 (+, -, *. /, %)

// 1. 더하기 연산자
// console.log( 1 + 1 );
// console.log( 1 + "1" );

// 2. 빼기 연산자
// console.log ( 1 - "2" ); // -1
// console.log ( 1 - 2); // -1

// 3. 곱하기 연산자
// console.log ( 2 * 3 ); // 6
// console.log ( 2 * "3" ); // 6

// 4. 나누기 연산자
// console.log ( 4 / 2 );
// console.log ( "4" / 2 );

// 5. 나누기 연산자(/) vs 나머지 연산자(%)
// console.log (5/2); // 2.5
// console.log (5 % 2); // 1

// 6. 할당 연산자 (assignment)
// 6-1. 등호 연산자 (=)
// let x = 10;
// console.log(x);

// // 6-2. 더하기 등호 연산자 (+=)
// x += 5;
// console.log(x);

// // 6-3. 빼기 등호 연산자 (-=)
// x -= 5;
// console.log(x);

// x -= 20;
// console.log(x);

// let a = 10;
// a *= 2;

// console.log(a);

// 비교 연산자 (어떠한 값을 비교해서 true 또는 false 값을 내는 연산자)
// 1. 일치 연산자 (===)
// 타입까지 일치해야 true 를 반환하는 연산자

// 숫자 2가 숫자 2랑 같아? ㅇㅇ
console.log( 2===2 ); // true
console.log ( "2"=== 2 ); // false

// 2. 불일치 연산자 (!==)
// 타입까지 일치해야 false 를 반환하는 연산자

// 숫자 2가 숫자 2와 달라? ㄴㄴ
console.log ( 2 !== 2); // false
console.log ( "2" !== 2); // true

// 3. 작다 연산자 (<)

// 2가 3보다 작아? ㅇㅇ
console.log("-----------");
console.log (2<3); // true

console.log (2 <= 3);
console.log (3 <= 3);


// 4. 논리 연산자
// 4-1 논리곱 연산자 (모두 true 일 때 true 반환)
console.log("----------")
console.log (true && true); //true
console.log (true && false); //false
console.log (false && true); // false
console.log (false && false); // false

// 4-2 논리합 연산자 ( 두 값 중 하나라도 true 인 경우 true 반환 )
console.log("------------")
console.log(true || true); //true
console.log(true || false); // true
console.log(false || true); //true
console.log (false || false); //flase

// 4-3 논리 부정 연산자
// : 값을 반대로 바꿈
console.log("------------")
console.log(!true);
let a = true;
console.log(!a);

// 5. 삼항 연산자 (중요)
// 조건에 따라 값을 선택한다.
let x = 4;
let result =  x > 5  ? "크다" : "작다";
console.log("--------")
console.log(result);


// 3항 연사자를 이용해서 y 가 10보다 작은 경우 작다를
// console.log 로 출력해주세요
console.log("--------")
let y = 9;
let result1 =  y > 10 ? "크다" : "작다" ;
console.log(result1);

// 6. 타입 연산자 (typeof)
console.log("--------")
console.log (typeof "5");

 

 

함수 = function (기능)

// 함수 = function (기능)
// input, output

// 1. 함수 선언문
// function add (매개변수) {
//     // 함수 내부에서 실행할 로직
// }

// 두 개의 숫자를 입력 받아서 덧셈을 한 후 내보내는 함수

function add (x, y) {

   return x + y ;
}

// 2. 함수 표현식
let add2 = function (x, y) {
    return x + y ;
}

// 함수를 호출한다 (= 사용한다)
// 함수명 () -> add()
// console.log(add (2, 3));

// let functionResult = add (3, 4);
// console.log (functionResult)

// 10 과 20 을 더한 값을 출력해보자

let functionResult2 = add2 (10, 20);
console.log (functionResult2);

// input : 함수의 input 부분 -> 매개 변수 (매개체가 되는 변수)
// output : retun 문 뒤에 오는 값 -> 반환값

 

스포크 (지역변수, 전역변수, 화살표함수)

//  스포크, 지역변수, 전역변수, 화살표함수
let x = 10;

function printX () {
    console.log(x);
}

console.log(x);
printX();

 

 

화살표 함수 (ES6 신 문법)

//화살표 함수
//ES6 신 문법
function add (x, y) {

    return x + y
}

// 1-1 기본적인 화살표 함수
let arrowFunc01 = (x, y) => {

    return x + y
}

// 1-2 한 줄로 (중괄호 안에 있는 줄이 한 줄이면 가능, 여러줄이면 불가능 {} 중괄호 를 생략할 수 없으니까)
let arrowFunc02 = (x, y) => x + y

//

function testFunc (x) {

    return x;
}

// 화살표 함수로

let arrowFunc03 = x => x

 

 

조건문 ( if, else if, switch )

// 조건문 (if, else if, else switch)
// 1. if 문
// let x = 10;
//      // () 안에 true 나 false 가 나올 수 있는 조건이 들어감
// if ( x > 0) {
//     console.log ("x는 양수입니다.")
// }


// 1-2
// let y = "hello world"

// // y 의 길이가 5보다 크거나 같으면 길이를 console.log 로 출력해줘

// if (y.length >= 5 ) {
//     console.log (y.length)
// }

// 2. if - else 문

// let x = -3;

// if ( x > 0) {
//     console.log ("x는 양수입니다")

// }

// else {
//     console.log ("x는 음수입니다")

// }

// if - else if - else 문


// let x = -1;

// if ( x < 0 ) {
//     console.log ("1");

// } else if ( x >= 0 && x < 10 ) {
//     console.log ("2");

// } else {
//     console.log ("3");

// }

// 1-4 switch 문
// 변수의 값에 따라 여러 개의 경우 (case) 중 하나를 선택
//default
let fruit = "양파"

switch (fruit) {
    case "사과":
        console.log("사과입니다.");
        break;
    case "바나나":
        console.log("바나나입니다.");
        break;
    case "키위":
        console.log("키위입니다.");
        break;
    default:
        console.log("아무것도 아입니다.");
        break;

}

 

조건문의 중첩으로 성인 남성, 여성 미성년 여성, 남성을 출력해주는 코드

// 조건문의 중첩
let age = 21;
let gender = "여성";

//미성년자 구분

if (age >= 18) {
    if (gender === "여성") {
        console.log("성인 여성입니다.");
    } else {
        console.log("성인 남성입니다.");
    }
} else {
    if (gender === "여성") {
        console.log("미성년 여성입니다.");
    } else {
        console.log("미성년 남성입니다.");
    }
}

 

 

조건부 실행

// 조건부 실행
// let x = 10;


// if ( x > 0 ) {
//     console.log ("x는 양수입니다.");

// }

// and 조건 (&&)
// ( x > 0 ) && console.log ("x 는 양수입니다.");



//or조건 (||)
//삼항 연산자와 단축평가
let y; //y 는 undefined
let z = y || 20;
// y 라는 값은 선언만 해놓고 값 할당 x y 는 undefined = z 라는 값에는 y 가 undefined 면 기본값을 세팅해

console.log (z);


 

 

falcy 한 값, truthly 한 값

// falcy 한 값, truthy 한 값

if (0) {
    console.log ("hello");
}

if ("") {
    console.log ("hello");
}

if (null) {
    console.log ("hello");
}

if (undefined) {
    console.log ("hello");
}

if (NaN) {
    console.log ("hello");
}

if (false) {
    console.log ("hello");
}

if (true) {
    console.log ("hello");

}

 

객체

// 객체
// key = value pair
// 하나의 변수에 여러개의 값을 넣을 수 있다.

// 1. 객체 생성 방법
// 1-1 기본적인 객체 생성 방법


// 1-2 생성자 함수를 이용하 객체 생성 방법
// function Person(name, age, gender) {
//     this.name = name;
//     this.age = age;
//     this.gender = gender;
// }

// let Person1 = new Person("홍길동", 30, "남자");
// let Person2 = new Person("홍길순", 20, "여자");

// 2. 접근하는 방법
// console.log ("1", person.name);
// console.log ("2", person.age);
// console.log ("3", person.gender);


// 3. 객체 메소드 (객체가 가진 여러가지 기능 : object. ~~~)
// 3-1 Object.key () : key 를 가져오는 메소드

// let person = {
//     name : "홍길동",
//     age : 30,
//     gender : "남자",
// };

// let keys = Object.keys(person);
// console.log ("keys => ", keys);

// 3-2 values

// let values = Object.values(person);
// // console.log ("values =>", values);

// // 3-1 entries
// // key 와 value 를 묶어서 배열로 만든 배열 (2차원 배열)
// let entries = Object.entries(person);
// // console.log ("entries =>", entries);

// // 3-4 asign
// // 객체 복사
// let newPerson = {};
// Object.assign(newPerson, person, {gender : "여자"});
// // console.log ("newPerson =>", newPerson);

// // 3-5 객체 비교
// // 객체는 크기가 상당히 큼 -> 메모리에 저장할 때 별도의 공간에 저장
// // person1 별도 공간에 대한 주소
// let person1 = {
//     name : "홍길동",
//     age : 30,
//     gender : "남자",
// };
// // person2 별도 공간에 대한 주소
// let person2 = {
//     name : "홍길동",
//     age : 30,
//     gender : "남자",
// };

// let str1 = "aaa";
// let str2 = "aaa";

// console.log (person1 === person2);
// console.log (str1  ===  str2);


// 3-6 객체 병합
let person1 = {
    name: "홍길동",
    age: 30,
};

let person2 = {
    gender: "남자",
};

// ... : spread operator
let perfectMan = {...person1, ...person2};
console.log (perfectMan);

 

배열

// 배열

// 1. 생성
// 1-1 기본 생성
// let fruits = ["사과", "바나나", "오렌지"];

// 1-2 크기 지정
let number = new Array(5);
// console.log (number.length);
// console.log (fruits.length);

// 2. 요소 접근
// console.log(fruits [0]);
// console.log(fruits [1]);
// console.log(fruits [2]);

// 3. 배열 메소드
// 3-1 push
// let fruits = ["사과", "바나나"];
// console.log ("1 => ", fruits);

// fruits.push("오렌지");
// console.log ("2 => ", fruits);

// 3-2 pop 배열의 마지막 요소가 없어짐
// let fruits = ["사과", "바나나"];
// console.log ("1 => ", fruits);
// fruits.pop();
// console.log ("2 => ", fruits);
 
// 3-3 shift 배열의 첫 요소가 없어짐
// let fruits = ["사과", "바나나", "키위"];
// console.log ("1 => ", fruits);
// fruits.shift ();
// console.log ("2 => ", fruits);

// 3-4 unshift 배열의 첫 요소에 추가
// fruits.unshift("포도");
// console.log (fruits);



// 3-5 splice
// fruits.splice (1, 1, "포도");
// // 1번부터 1개 지우고 포도를 넣어줘
// console.log (fruits);

// 3-6 slice
// let sliecedFruits = fruits.slice(1, 2);
// console.log (sliecedFruits);

// let fruits = ["사과", "바나나", "키위"];

// forEach, map, filter, find
// let numbers = [4, 1, 5, 4, 5];

// 매개변수 자리에 함수를 넣는 것 = 콜백 함수
// numbers.forEach(function(item){
//     console.log ("item 입니다 =>", + item);
// });

// (2) map

// let newNumbers = numbers.map(function(item){
//     return item * 2;
// });

// console.log (newNumbers);

// let numbers = [4, 1, 5, 4, 5];

// let filterdNumbers = numbers.filter(function(item){

//     return item === 5
// });

// console.log (filterdNumbers);

let numbers = [4, 1, 5, 4, 5];

let result = numbers.find(function(item){
    return item > 3;
});
console.log (result);

 

for, while ( ~ 동안 : 반복문)

// for, while => ~동안 : 반복문
// for (초기값; 조건식; 증강식) {
// }

// i라는 변수는 0부터 시작한다
// i라는 변수가 10에 도달하기 전까지 계속한다
// i라는 변수는 한 사이클이 돌고 나면 1을 더한다
// for (let i = 0; i < 10; i++) {
//     console.log("FOR문 돌아가고 있음 => " + i);
// }

// 배열과 for 문은 짝궁이다.
// const arr = ["one", "two", "three", "four", "five"];
// for (let i = 0; i < arr.length; i++) {
//     console.log (i);
//     console.log (arr[i]);
// }

// ex : 0부터 10까지의 수 중에서 2의 배수만 console.log 로 출력하는 예시

// for (let i = 0; i < 11; i++) {
//     if (i >= 2) {
//         if (i % 2 === 0) {
//             console.log(i + "는 2의 배수입니다.");
//         }
//     }
// }

// for ~ in 문
// 객체의 속성을 출력하는 문법
let person = {
    name: 'john',
    age: 20,
    gender: "male",
};

for(let key in person) {
    console.log (key + ": " + person[key]);
}

 

While

// while
// let i = 0;

// while ( i < 10 ) {
//     console.log (i);
//     i++;
// }

// while 문을 활용해서, 3초과 100 미만의 숫자 중 5의 배수인 것만 출력하는 예

// let i = 3;
// while (i < 100) {
//     if ( i % 5 === 0 && i >= 5 ) {
//         console.log ( i + "는 5의 배수입니다.")
//     }
   
//     i++;
// }

// do ~ while

// let i = 0;

// do {
//     console.log (i);
//     i++;
// } while (i < 10);

// for(let i = 0; i<10; i++) {
//     if (i === 5 ) {
//         break;
//     }
//     console.log (i);
//

// for(let i = 0; i<10; i++) {
//     if (i === 5 ) {
//         continue;
//     }
//     console.log (i);
// }


 

 

코드 스니펫 복사 붙여넣기가 아니라 강의를 들으며 내가 한땀 한땀 작성한 코드들을 옮겨왔다...

 

1주차부터 이렇게 어려워도 되는건가 싶은데, 다른 분들도 다 어렵다고 하시니,.. 근데 이걸 안심해야 할지.. 참 복합적이다.

 

벽을 느끼니 뭔가 조급한 마음이 드는데 이럴수록 침착함을 유지해야 한다는 건 누구보다 잘 알지만...

 

천천히 되새김질 하면서 차근차근 가보자.. 남는 게 시간인데 남들보다 더 하면 되겠지.

 

자바 스크립트가 현물로 존재했다면 맞짱 떠서 내 뇌에 강제로 쑤셔 넣고 싶다.