[TIL] JavaScript 문제집

Day7 🏁

질문 없이 구글링으로만 모든 문제를 다 풀었다!!!
오늘 백준은 쉬어야지 ㅎ ㅎㅎ ㅎㅎㅎ,,,

데이터 타입

원시 타입 (Primitive type)객체 타입 (Object type)
Number (숫자)Array (배열)
Strings (문자열)Function (함수)
Boolean (불리언)RegExp (정규표현식)
Undefined (정의되지 않음)
Null (널)
Symbol (ES6 추가)

String

리터럴 방식을 사용함 “ “ ‘ ‘ ` `

String 프로퍼티와 메서드

.split()

지정한 구분자를 이용하여 여러 개의 문자열로 나눕니다.

var str1 = "Hi!Elice";

str1.split("!");  // [Hi, Elice]

.charAt()

배열의 인덱스 값 반환

var str1 = "Hi!Elice";

str1.charAt(1);  // i

.length

문자데이터의 글자의 갯수를 반환.

const str = '0123'
console.log(str.length) //4

const str = '01 23'
console.log(str.length) //5(띄어쓰기도 갯수에 포함)

.indexOf()

호출한 string객체에서 주어진 값과 일치하는 첫번째 인덱스를 반환.

일치하는 값이 없으면 -1을 반환

const result = 'Hello world!'.indexOf('world')
console.log(result) //6

const result = 'Hello world!'.indexOf('안녕')
console.log(result) //-1

.slice()

문자열의 일부를 추출하면서 문자열을 반환

  • endIndex는 그 직전까지 추출됨(0, 3일경우 3의 직전까지 해당하는 2번까지의 인덱스 문자열을 반환)
const str = 'Hello world!'
console.log(str.slice(0, 3)) //Hel

.replace()

첫번째에 찾은 문자데이터에서 두번째에 있는 문자데이터로 대체됨

const str = 'Hello world!'
console.log(str.replace('world', '안녕') //Hello 안녕!

const str = 'Hello world!'
console.log(str.replace(' world!', '') //Hello

.match()

특정한 문자데이터에서 정규표현식을 통해 특정한문자를 일치시켜서 배열데이터로 반환

  • /.+(?=@/) 정규표현식(RegExp)
const str = '[email protected]'
console.log(str.match(/.+(?=@/)) //okdol0611을 포함한 배열데이터

const str = '[email protected]'
console.log(str.match(/.+(?=@/)[0]) //okdol0611

.trim()

문자데이터의 앞,뒤 공백을 없애줌(로그인창에서 아이디입력시 실수로 띄어쓰기를 할 경우 띄어쓰기도 문자데이터로 인식해서 오류나는것을 방지할때 쓸 수 있음)

const str = '    Hello world     '
console.log(str.trim()) //Hello world

Math

숫자데이터로 변환

const pi = 3.14159265358979
console.log(pi) //3.14159265358979

const integer = parseInt(str) 
//숫자가 들어있는 문자데이터를 넣으면 숫자만 추출돼서 정수(integer)로 반환
const float = parseFloat(str) 
//소수점자리 숫자도 유지하면서 문자데이터를 숫자로 변환

console.log(integer) //3
console.log(float) //3.14
console.log(typeof integer, typeof float) //number number

Math 프로퍼티와 메서드

.toFixed()

const pi = 3.14159265358979
console.log(pi) //3.14159265358979

const str = pi.toFixed(2)
// 메소드가 호출될때 인수로 소수점 몇번째자리까지 유지할것인지 표기해 문자데이터로 반환
console.log(str) //3.14
console.log(typeof str) //string

Math.abs()

console.log('abs: ', Math.abs(-12)) //abs: 12
//주어진 숫자의 절대값을 반환

Math.min()

console.log('min: ', Math.min(2, 8)) //min: 2
//인수로 들어온 숫자 데이터중에 가장 작은값을 반환

Math.max()

console.log('max: ', Math.max(2,8)) //max: 8
//인수로 들어온 숫자 데이터중에 가장 큰값을 반환

Math.ceil()

console.log('ceil: ', Math.ceil(3.14)) //ceil: 4
//올림처리된 값 반환

Math.floor()

console.log('floor: ', Math.floor(3.14)) //floor: 3
//내림처리된 값 반환

Math.round()

console.log('round: ', Math.round(3.14)) //round: 3
//반올림 처리 된 값 반환

random()

console.log('random: ', Math.random()) //random:  0.8935768296443671
//랜덤한 숫자(난수) 반환, 0이상 1미만의 부동 소숫점 난수를 반환합니다.

Array

서로 연관된 데이터를 모아서 그룹핑 한 후에 이름을 붙인 것이 배열이다.

[] //빈 배열
[ 1, 2, 3, 4, 5 ]
[ 1, 'A', true, null ]

Array 메서드

.length

배열데이터에 들어있는 아이템의 갯수를 반환

const numbers = [1, 2, 3, 4]
console.log(numers.length) //4

console.log([1,2].length) //2
//배열리터럴에 직접적으로도 사용할 수 있음

console.log([].length) //0
//빈 배열, 배열에 데이터가 채워져있는지 아닌지 확인할 수 있음

.push

배열데이터 끝에 아이템을 추가

const fruits = ['사과', '바나나', '체리']
fruits.push('오렌지')

console.log(fruits) //(4) ['사과', '바나나', '체리', '오렌지']

.concat()

두개의 배열데이터를 병합해서 새로운 배열데이터를 반환

  • 원본의 데이터는 손상이 되지 않음
const numbers = [1, 2, 3, 4]
const fruits = ['사과', '바나나', '체리']

console.log(numbers.concat(fruits)) //(7) [1, 2, 3, 4, '사과', '바나나', '체리']
console.log(numers) //(4) [1, 2, 3, 4]
console.log(fruits) //(3) ['사과', '바나나', '체리']
//다시 각각 출력해도 원본의 데이터 손상 X

.forEach()

아이템의 갯수만큼 특정한 콜백함수를 반복적으로 실행(반환되는 값 없음)

  • 콜백함수 : 함수형태의 파라미터를 전달(쉽게말해서 함수 안에 함수)
  • 사실 array 는 잘 사용하지 않음
  • index = i 로 줄여서 사용 가능
const fruits = ['사과', '바나나', '체리']

fruits.forEach(function (item, i, array) {
	console.log(item, i, array)
})
//사과 0 (3) ['사과', '바나나', '체리']
//바나나 1 (3) ['사과', '바나나', '체리']
//체리 2 (3) ['사과', '바나나', '체리']

.map()

아이템의 갯수만큼 콜백반복 + 콜백함수 내부에서 return키워드를 통해 반환하는 데이터를 병합해 새로운 배열을 만들어서 사용

  • .forEach() 는 따로 반환되는 값이 없음
const numbers = [1, 2, 3, 4]
const fruits = ['사과', '바나나', '체리']

const a = fruits.forEach((fruit, index) => {
	console.log(`${fruit}-${index}`)
})
console.log(a)
//사과-0
//바나나-1
//체리-2
//undefined

const b = fruits.map((fruit, index) => `${fruit}-${index}`)
console.log(b) //(3) [사과-0, 바나나-1, 체리-2]
  • 객체 리터럴 {} 을 이용한 예제
const fruits = ['사과', '바나나', '체리']

const b = fruits.map((fruit, index) => ({
		id: index,
		name: fruit
	}))
console.log(b) //(3) [{id:0, name: "사과"}, {...}, {...}]

산술 연산자(arithmetic operator)

console.log(1 + 2)
console.log(5 - 7)
console.log(3 * 4)
console.log(10 / 2)
console.log(7 % 5) //나머지 2

var value = 10
console.log(++value) //11
console.log(--value) //10

- 증감연산자 전위, 후위(++n, n++) 차이

문제를 풀다가 내 생각과 다른 값이 나와서 찾아보았다.

  • 증감연산자는 증가연산자(++)와 감소연산자(--)로 나뉜다.
    증가연산자는 변수값을 1 증가시키고 감소연산자는 변수값을 1 감소시킨다.
  • 또한 증감연산자는 전위(++n)와 후위(n++)로 나뉜다.
    전위나 후위나 증감연산자가 사용된 후의 n을 출력하면 1이 증가된 값을 갖게된다.
int a = 1, b = 1, c = 1, d = 1;
 
	++a;
	b++;
	c = c + 1;
	d += 1;
 
	printf("출력값: %d, %d, %d, %d\n", a, b, c, d);	
  		  /* 다음의 결과값은 모두 2다.
  		  출력값: 2, 2, 2, 2 */

전위 (++n)

연산자 ++가 피연산자 n보다 앞에 위치할 때를 전위라 하고 1증가된 값이 연산결과값이다.

후위 (n++)

반대로 연산자 ++가 피연산자 n보다 뒤에 위치할 때를 후위라 하고 1증가하기 전 값이 연산결과값이다.

그렇다면 연산결과값이 뭘까, 간단히 말해 '증감연산 그 자체의 값' 이다.

다시말해 'n++이나 ++n' 그 자체의 결과값을 말한다.

int a = 1, b = 1;
 
printf("출력값: %d, %d \n", ++a, b++);
	/* 출력값: 2, 1 */

전위인 경우 1증가된 후의 값인 2가 나왔고, 후위인 경우 1증가되기 전의 값인 1이 나왔다.

다시말해 서로 다른 '연산결과값'이 나왔으며 이것이 전위와 후위의 차이점이다.

위의 내용을 그림으로 표현하면 다음과 같다.

(이미지 출처)

전위일 때와 후위일 때, 연산결과값은 서로 다르지만 연산이 끝난 후 n의 값은 둘 다 11로 같다는 것 또한 잊지말자.

비교 연산자

comparison operator

const a = 1
const b = 1

console.log(a === b) //true
//=== 일치연산자 : 가운데연산자를 기준으로 왼쪽,오른쪽 데이터를 비교해서 일치하는지를 확인함 

function isEqual(x, y) {
    return x === y
}

console.log(isEqual(1, 1)) //true
console.log(isEqual(2, '2')) //false
const a = 1
const b = 3

console.log(a !== b) // true
// !== 불일치연산자 : 서로 다른값인지 확인해줌

console.log(a < b) //true
console.log(a > b) //false

const x = 13
const y = 13

console.log(x >= y) //true
console.log(x <= y) //true
// =기호를 <>괄호보다 뒤에 적어야함

논리 연산자

logical operator

const a = 1 === 1
const b = 'AB' === 'AB'
const c = false

console.log(a) //true
console.log(b) //true
console.log(c) //false

console.log('&&: ', a && b && c) //&&: false
// && 그리고, end연산자 : 모든값이 true 인가? 하나라도 false값이 있느면 false가됨
console.log('||: ', a || b) //||: 'true
// || 또는, or 연산자 : 모든값중에 true라는 값이 하나라도 있으면 true
console.log('!: ', !a) //!: false
// ! 부정, not 연산자 : 뒤쪽에있는 데이터가 true면 false, false면 true로 반대값을 출력함

할당 연산자

assignment operator

// 할당 연산자

let a = 2 // = 할당연산자
//const : 재할당불가능 , let : 재할당 가능
// a = a + 1 아래랑 같은 의미
a += 1 //-, *, /, % 연산자 모두 대입 가능함

console.log(a) //3

출처 📚

좋은 웹페이지 즐겨찾기