본문으로 바로가기

코테 문법

category JavaScript 2024. 11. 26. 15:52

오늘은 현재까지 진행한 알고리즘 코드카타에서 헷갈렸거나 중요하다고 생각하는 자바스크립트 문법 정리를 해보려 합니다... 오랜만에 코테 연습해보니까 반환값이 있었는지 없었는지도 기억이 잘 안 나네요...ㅜ 꾸준히 프로그래머스에서 문제 풀면서 문법 잊지 않도록 해야할 거 같습니다!

 

 

대충 한 20문제 푸는동안 reduce, filter 등등 적용해보려다가 안돼서 그냥 for문 이용한 것도 있어서 확실하게 정리하고자 자바스크립트 문법 검색해서 공부해 보았습니다. 모든 문제 다 정리하기보다 이 문법이 있었다는 것이 기억은 나는데 막상 쓰려니까 잘 안 된 문법 위주로 정리를....

 

 

 

 

 

 

 

1. 수식 관련 문법

- Math.floor()

  숫자에서 소수점 이하를 버리고 내림

 

- Math.ceil()

  숫자에서 소수점 이하를 버리고 반올림

 

- Math.round()

 숫자를 반올림하여 가장 가까운 정수로 변환

 

- Math.sqrt()

 숫자의 제곱근을 반환

 

- Math.pow()

 숫자의 거듭제곱을 계산

 

- Math.abs()

  숫자의 절댓값을 반환

 

Math - JavaScript | MDN

Math 는 수학적인 상수와 함수를 위한 속성과 메서드를 가진 내장 객체입니다. 함수 객체가 아닙니다.

developer.mozilla.org

 

2. 배열 메서드

- forEach()

  • 배열을 순회하면서 각 요소에 대해 주어진 함수를 실행
  • return : undefinend (반환값 없음) 
const array1 = ['a', 'b', 'c'];

array1.forEach((element, index) => console.log(`${index} : ${element}`));

// Expected output: "0 : a"
// Expected output: "1 : b"
// Expected output: "2 : c"

 

- map()

  • 배열의 각 요소를 변형하거나 메핑하여 새로운 배열을 반환함
  • return : 새로운 배열 (원본 배열은 변하지 않음)
const array1 = [1, 4, 9, 16];

// Pass a function to map
const map1 = array1.map((x) => x * 2);

console.log(map1);
console.log(array1);
// Expected output: Array [2, 8, 18, 32]
// Expected output: Array [1, 4, 9 , 16]

 

- filter()

  • 배열에서 조건을 만족하는 요소들만 추출하여 새로운 배열을 반환
  • return : 조건에 맞는 새로운 배열
const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter((word) => word.length > 6);

console.log(result);
console.log(words);
// Expected output: Array ["exuberant", "destruction", "present"]
// Expected output: Array ['spray', 'elite', 'exuberant', 'destruction', 'present']

 

- reduce()

  • 배열을 순회하면서 하나의 값으로 축소(합계나 평균을 구할 때 사용)
  • return : 축소된 결과 값
const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce((accumulator, currentValue) => accumulator + currentValue, initialValue);

console.log(sumWithInitial);
// Expected output: 10

 

- sort()

  • 배열의 요소를 정렬
  • 정렬된 배열
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// Expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// Expected output: Array [1, 100000, 21, 30, 4]
// 문자열 기준으로 배열했기 때문에 100000이 중간에 있음

// 오름차순 정렬(숫자 배열)
const arr = [4, 1, 3, 2];
arr.sort((a, b) => a - b); // 내림차순 정렬일 때는 b-a
console.log(arr);

 

- push()

  • 배열의 끝에 요소를 추가
  • return : 배열의 새로운 길이 (변경된 배열)
const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('cows');
console.log(count);
// Expected output: 4
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

 

- pop()

  • 배열의 끝에서 요소를 제거
  • return : 제거된 요소
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// Expected output: "tomato"

console.log(plants);
// Expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

plants.pop();

console.log(plants);
// Expected output: Array ["broccoli", "cauliflower", "cabbage"]

 

- concat()

  • 하나 이상의 배열이나 값을 기존 배열에 합침
  • return : 새로운 배열 (원본 배열은 변하지 않음)
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
// Expected output: Array ["a", "b", "c", "d", "e", "f"]

 

- split()

  • 문자열을 구분자를 기준으로 나누어 배열로 반환
  • return : 새로운 배열 (원본 배열은 변하지 않음)
const str = 'The quick brown fox jumps over the lazy dog.';

const words = str.split(' ');
console.log(words[3]);
// Expected output: "fox"

const chars = str.split('');
console.log(chars[8]);
// Expected output: "k"
// 빈 배열을 지우고 싶다면? filter를 이용하여 (char !== '')

const strCopy = str.split();
console.log(strCopy);
// Expected output: Array ["The quick brown fox jumps over the lazy dog."]

 

- join()

  • 배열의 모든 요소를 결합하여 하나의 문자열로 반환
  • return : 배열을 결합한 문자열
const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// Expected output: "Fire,Air,Water"

console.log(elements.join(''));
// Expected output: "FireAirWater"

console.log(elements.join('-'));
// Expected output: "Fire-Air-Water"

 

- slice()

  • 배열의 일부를 추출하여 새로운 배열을 반환
  • return : 추출된 새로운 배열
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]
// animals[2]까지

console.log(animals.slice(2, 4)); // (a, b)라 치면 a부터 b-1까지
// Expected output: Array ["camel", "duck"]
// animals[2], animals[3]

console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]

console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

 

 

 

Array - JavaScript | MDN

다른 프로그래밍 언어의 배열과 마찬가지로, Array 객체는 여러 항목의 컬렉션을 단일 변수 이름 아래 저장할 수 있고, 일반적인 배열 연산을 수행하기 위한 멤버가 있습니다.

developer.mozilla.org