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

Kimyeongkyung

자바스크립트 기초문법 정리 본문

important

자바스크립트 기초문법 정리

yeongk0825 2022. 3. 13. 02:08

switch문

 

console.log('Menu');
console.log('1.아이스아메리카노');
console.log('2.카페라떼');
console.log('3.카푸치노');

var choice = parseInt(prompt("메뉴 선택"));

console.log(choice+"번");

switch(choice){
  case 1:
  console.log("1500");
    // break;
  case 2:
    console.log("2000");
    break;
  case 3 :
    console.log("2500");
    // break;

  default:
    console.log("그런메뉴 없음");
  break;  
}

 

 

for문

Q. for문을 이용해서 배열 cost의 값을 모두 더해 total_cost 변수에 저장하세요.

var cost = [ 85, 42, 37, 10, 22, 8, 15 ];
var total_cost = 0;
for(var i=0;i<cost.length;i++){

//각 배열의 index값을 나타냄. index는 0부터 시작하니까 0으로 선언
    total_cost += cost[i];
    //total_cost = total_cost + cost[1]+cost[2]+...+cost[배열의 마지막 값까지];
    //index는 0부터 세니까 배열의 길이만큼 for문을 돌리고, 배열의 길이보다는 작거나 같다 가 아니라 작아야 함.
    즉 var cost의 배열의 길이는 7이니까 index값은 [0]~[6]
}

console.log(total_cost);

 

 

for in문

var box = {name:"object",weight:30,isObject:true,arr:[1,2,3]obj:{property:1}};

 

var property_list = object.keys(box);console.log("Property List:", property_list);

 

//object.keys(box);//출력값 => ["name", "weight", "isObject", "arr", "obj"]

 

for(var i=0;i<property_list.length;i++){

 var propertyName = property_list[i];

console.log(propertyName,": ",obj[propertyName]);

}

 

----------------------------------------------------------for(var propertyName in obj){console.log(propertyName,": ",obj[propertyName]);}

 

참고

object.keys(객체 이름)

객체를 만들다 보면 상황에 따라서는 객체의 key값만 가지고 오고 싶을 때도 있다. 

Object.keys() 메서드는 객체(typeof 연산자로 확인했을 때 object가 반환되는)의 프로퍼티들 중에서 key값, 다른 말로 프로퍼티 네임들만 묶어서 배열로 반환하는 메서드이다. 

 

 

"객체의 propertyName" in 객체 이름;

 

객체 안에 객체의 propertyName 이 들어있나요?

=>true(존재할 경우) / false(존재하지 않을 경우)

 

객체에 존재하지 않는 속성에 접근하면 undefined 반환

 

속성의 이름에 접근하기 전에 in 연산자를 활용하면 객체에 해당 속성이 존재하는지를 미리 확인할 수 있음(꿀팁)

 

.reduce

=>배열의 모든값 더하기

우리가 원하는 시작점부터 모든 배열을 돌면서 어떤 값을 누적할때 사용

 

const result = 배열이름.reduce((prev, curr) =>{
console.log(prev);
console.log(curr);
return prev + curr.score;
}, 0);

console.log(result);

초기값을 0으로 설정하는 이유는 배열의 첫번째 값을 0으로 시작하기 위함

 

줄여서 쓸 수도 있음

.reduce((prev, curr) => prev + curr, 0);

 

.reduceRight

: 배열의 뒤에서부터 더해서 누적

 

.join

: 배열을 string으로 변화시켜줌

 

const fruite = ['사과','바나나','오렌지'];

const result = fruits.join(','); //구분자를 넣지않아도 자동으로 콤마가 들어간 string이 출력됨

console.log(result);

 

출력값

: 사과,바나나,오렌지

 

.

.split(구분자, limit)

: string을 배열로 만들어주는 메서드

limit은 넣어도되고 안넣어도 되는데 만약 넣을 경우 원하는 배열의 개수만을 출력

 

const fruits = '사과, 키위, 바나나, 딸기';

 

const result = fruits.split(',');

console.log(result);

 

출력값

["사과","키위","바나나","딸기"]

 

const result = fruits.split(',' , 2);

console.log(result);

 

출력값

["사과","키위"]

 

구분자를 꼭 넣어줘야함. .split()와 같이 빈 공백을 주면 안됨

문자열 전체가 배열 안에 들어가게 됨

 

출력값

["사과, 키위, 바나나, 딸기"]

 

.reverse

배열안에 들어있는 아이템의 순서를 거꾸로 만들어줌

 

배열자체를 변화시키기 때문에(splice도 같은 성격)

다시 원래 배열을 반환시켜도 배열이 거꾸로되어있음

 

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

const result = array.reverse();

console.log(result);

=> 출력값 [5,4,3,2,1]

console.log(array);

=> 출력값 [5,4,3,2,1]

이미 reverse된 배열은 다시 원래 배열 array를 return 해도 배열이 바뀌어 있음

 

.slice(start,end) 

: 배열에서 원하는 부분만 받아오고 싶을때 사용

 

배열안에서 start 지점부터 end 까지. (단, end에 해당하는 값은 포함하지않음)

          index  [0] [1] [2] [3] [4] 

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

const result = array.slice(2,4) // 배열 안 숫자 5는 포함되지 않음

출력값 => [3,4]

이후 원래 배열인 array를 다시 출력하면 splice처럼 바뀌지 않고 다시 [1,2,3,4,5]로 리셋됨

console.log(array)

출력값 => [1,2,3,4,5]

 

.splice(start,개수)

 

배열의 특정 위치에 배열 요소를 추가하거나 삭제하는데 사용. 
return 값은 삭제한 배열 요소. 만약 삭제한 요소가 없더라도 빈 배열을 반환함.

 

start 부터 몇개를 삭제할건지(배열 자체를 변화시킴)

 

          index  [0] [1] [2] [3] [4] 

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

const result = array.splice(0,2) // 인덱스 0부터 2개 삭제

console.log(result);

출력값 => [1,2]

console.log(array);

출력값 =>[3,4,5]

 

.pop()

배열의 마지막 요소를 제거한 후, 제거한 요소를 반환

pop와 splice와의 차이점은 pop()는 배열이 아닌 요소를 반환, arr = [1,2,3]에서 pop() => 3 반환
splice()는 삭제한 값의 배열을 반환, arr = [1,2,3]에서 splice(-1) => [3] 반환

 

-----------------------------------------------------------------------------------------------------------------------------------

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, 80),
  new Student('C', 30, true, 90),
  new Student('D', 40, false, 66),
  new Student('E', 18, true, 88),
];

 



.find()

const result  = students.find(function(student,index){

  return student.score === 90;

  console.log(result);

});

 

축약형

 

const result  = students.find((student) => student.score === 90;)

  console.log(result);

 

.filter

콜백함수가 true인 것만 모아서 새로운 배열을 전달해주는 아이

 

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

console.log(result);

 

출력값

enrolled 가 true인 학생들의 배열만 나오게 됨

 

.map

: 우리가 전달한 콜백함수를 통해 다른 새로운 값으로 변환시킴

* 콜백함수로 전달되는 인자 이름은 이해하기 쉽도록 쓰는것이 좋음

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

                                                          -> 원하는 콜백함수 만들기(ex. student.score*2 => student)

console.log(result);

 

출력값

[45,80,90,66,88]

 

참고자료

 

map함수는 callbackFunction을 실행한 결과를 가지고 새로운 배열을 만들 때 사용한다.

array.map(callbackFunction(currenValue, index, array), thisArg)

filter, forEach와 같은 구문이다.

callbackFunction, thisArg 두개의 매개변수가 있고
callbackFunction은 currentValue, index, array 3개의 매개변수를 갖는다.

  • currentValue : 배열 내 현재 값
  • index : 배열 내 현재 값의 인덱스
  • array : 현재 배열
  • thisArg : callbackFunction 내에서 this로 사용될 값

출처 - https://velog.io/@daybreak/Javascript-map%ED%95%A8%EC%88%98

 

.some

어떤것이라도 하나 만족되는게 있는지 없는지 검사할때 사용

const result = students.some((student) => student.score < 50);

// score가 50점 미만인 student가 한명이라도 있으면 true 반환

 

console.log(result);

 

출력값 : true

 

.every

모든 배열의 조건이 만족되어야 할때 사용

const result = students.some((student) => student.score >= 50);

// 배열에 있는 모든 요소들이 이 조건을 만족해야만 true 반환

 

console.log(result);

 

출력값 : false

 

.sort

 

const result = students

 .map(student => student.score) //score만 출력

 .sort((a, b)=>a-b) //작은 수부터 큰 수 => b-a로 바꾸면 큰 수부터 정렬

 .join(); //string화

console.log(result);

 

출력값 = 45,66,80,88,90

 

 

참고자료

https://www.youtube.com/watch?v=FN_D4Ihs3LE