공부 이야기

[개발] 문과생의 Java Script 공부 (1)

창이 2023. 12. 10.
728x90
반응형

 

java script에 대한 공부를 하려고 한다.

해당 데이터에 쓴 내용들은 인프런 강의 중

코드 팩토리님의 강의를 듣고 다시 적어본 내용들이다. 

var name = 'bumchang';
console.log(name);
let ive = 'chnag';
console.log(ive);

 

* 변수 선언 

var는 더 이상 쓰지 않는다. 하지만, 예전부터 var를 써왔던 곳이라면 쓸 수 있어야 함. let과 var로 변수를 선언하면 값을 추후 변경할 수 있으나, const로 변수 선언을 하면 추후 값 변경이 불가능하다. 

 

 

 변수 이름 지을 때 
 1) 일반적으로 영어를 사용하며 문자 숫자 모두 사용 가능 
 2) 특수 기호는 언더스코어와 달러를
 3) 숫자로 이름을 시작할 수 없다 
 4) 키워드는 변수명으로 사용 x 

 

 * naming convention2
 1) camelCase : 대부분 언어 사용 (첫 글자 소문자 / 뛰어쓰기 후 첫글자는 대문자)
 2) snake_case : 파이썬 등 
 3) PascalCase : C# 마이크로소프트 계열

 

 * data types 
 1) Number
 2) String
 3) Boolean
 4) undefined

 5) null
 6) Symbol
 7) Object

    Function
    Array
   Object

 

 

* Array type

> 값을 리스트로 나열할 수 있는 타입 

 

const iveMemberArrary = [
    '안유진',
    '레이',
    '장원영',
    '이서',
    '리즈',
];
console.log(iveMemberArrary);


 * 삼항조건연산자 

console.log(10 > 0 ? '10이 0보다 크다' : '10이 0보다 작다');

 

 * 단축 평가 ( short circuit evaluation)
 
 - && 사용했을 때 좌측이 true면 우측 값 반환
 - && 사용했을 때 좌측이 false면 좌측 값 반환
 - || 사용했을 때 좌측이 true면 좌측 값 반환 
 - || 사용했을 때 좌측이 false면 우측 값 반환 

 

* if and switch 

/**
 * If and Switch
 */

let number = 5;

if (number % 2 === 0) {
    console.log('number 변수는 짝수입니다.');
} else {
    console.log('number 변수는 홀수입니다.');
}

const englishDay = '토요일';
let koreanDay;

switch(englishDay){
    case 'monday':
        koreanDay = '월요일';
        break;
    case 'tuesday':
        koreanDay = '화요일';
        break;
    case 'tuesday':
        koreanDay = '수요일';
        break;
    case 'tuesday':
        koreanDay = '목요일';
        break;
    case 'tuesday':
        koreanDay = '금요일';
        break;
    default:
        koreanDay = '주말';
        break;
} 

console.log(koreanDay);

 

* type conversion 

1) 명시적 

let age = 32;
let stringAge = age.toString();
console.log(typeof stringAge, stirngAge);

 

2) 암묵적

let test = age + '';
console.log(typeof test, test);

console.log('98' + 2); 
console.log('98' * 2);

 

 

* Array Function 

 

/**
 * Array Function 
 */

let iveMembers = [
    '안유진',
    '가을',
    '레이',
    '장원영',
    '리즈',
    '이서',
];

console.log(iveMembers);

 

* push & pop & shift

iveMembers.push('범창');
console.log(iveMembers);

//pop > 마지막 element 삭제
console.log(iveMembers.pop());
console.log(iveMembers);

//shift() > 처음 element 삭제 
console.log(iveMembers.shift());
console.log(iveMembers);


* concat() / slice() / spread operator / join() / sort() 

spread operator -> 상위 LIST에다가 펼쳐서 넣을 수 있다. 

 

iveMembers = [
    '안유진',
    '가을',
    '레이',
    '장원영',
    '리즈',
    '이서',
];
console.log('------------------');

console.log(iveMembers.concat('코드팩토리')); // 아예 다른 메모리 공간에 저장된 값이 반환 
console.log(iveMembers);

console.log(iveMembers.slice(0, 3));
console.log(iveMembers); //원래 Array는 변하지 않는 방법임 

// spread operator

let iveMembers2 = [
    ...iveMembers,
];
console.log(iveMembers2);


//join()
console.log(iveMembers.join());
console.log(iveMembers.join('/'));
console.log(iveMembers.join(', '));

//sort()
// 오름차순
iveMembers.sort();
console.log(iveMembers);

//내림차순
console.log(iveMembers.reverse());

let numbers = [
    1,
    9,
    7,
    5,
    3,
];

console.log(numbers);

 

* map()

-> array에 있는 모든 값들을 순회하며 각 값들을 변형시키는 역할 

 

** filter() / find() / findIndex() / reduce() / 

 

find() -> 모조건 한 개 반환 

findIndex() -> 인덱스 반환 

// map()
// array에 있는 모든 값들을 순회하며 각 값들을 변형시키는 역할
console.log('----------------------');
console.log(iveMembers.map((x) => `아이브: ${x}`));

console.log(iveMembers.map((x) => {
    if(x === '안유진'){
        return `아이브: ${x}`;
    }else{
        return x;
    }
}));
//원래 array를 바꾸지 않고 새로운 array를 변환해준다 

//filter()
numbers = [1, 8, 7, 6, 3];

//짝수 필터링
console.log(numbers.filter((x) => x % 2 === 0 ));

//find()
//무조건 한 개 반환
console.log(numbers.find((x) => x % 2 === 0));

//findIndex()
//인덱스 반환
console.log(numbers.findIndex((x) => x % 2 === 0));

//reduce()
console.log(numbers.reduce((p, n) => p + n,0));

// 설명
// p, n 부분 콜백함수, 0은 초기값 
//

 

* object -> 객체 

 

key와 value로 이루어져 있음


 * 객체 특징
1) const로 선언할 경우 객체 자체를 변경할 수 없다
2) 객체 안의 프로퍼티나 메서드는 변경할 수 있다 
 

let yuJin = {
	name : '안유진',
    group : '아이브',
    dance : function(){
    	retrun `${this.name}이 춤을 춥니다.`;
    };
    
    console.log(yuJin.name);
    console.log(yuJin.dance());
    
    const nameKey = 'name';
const nameValue = '안유진';

const groupKey = 'group';
const groupValue = '아이브';

const yuJin2 = {
    [nameKey] : nameValue,
    [groupKey] : groupValue,
    dance : function(){
        return `${this.name}이 춤을 춥니다`;
    }
}
console.log(yuJin2);
console.log(yuJin2.dance());

yuJin2['group'] = '코드팩토리';
console.log(yuJin2);

yuJin2['englisgName'] = 'An Yu Jin';
console.log(yuJin2);


const wonYoung = {
    name : '장원영',
    group : '아이브',
}
console.log(wonYoung);

// wonYoung = {};

wonYoung['group'] = '코드팩토리';
console.log(wonYoung);

/**
 * 모든 키 값 다 가져오기 
 */

console.log(Object.keys(wonYoung));

/**
 * 모든 밸류 값 다 가져오기
 */
console.log(Object.values(wonYoung));

const name = '안유진';
const yuJin3 = {
    name,
};
console.log(yuJin3);

 

 

* function 

만약 2라는 숫자에 * 10 / 2 % 3을 스트링으로 변환해서 반환받고 싶다면 어떻게? 

console.log((2*10/2%3).toString());

function calculate(){
    console.log((2*10/2%3).toString());
}

function calculate(number){
    console.log((number*10/2%3).toString());
}

calculate(4);

 

** 함수에서 입력 받는 값에 대한 정의를 Parameter / 실제 입력하는 값은 argument 

-> 반환받을 때 쓰는 함수 : return 

 

** 함수의 다른 형태 : arrow 함수 

 

const multiply4 = (x, y) => {
    return x * y;
}
console.log(multiply4(3, 4));

const multiply3 = (x, y) => x*y;
console.log(multiply3(3, 4));

 

728x90
반응형

댓글

추천 글