자바스크립트 1주차 복습

Minju Kang·2023년 8월 5일
1

Window 객체

  1. 브라우저 안의 모든 요소들이 소속된 객체, 최상 위에 있기 때문에 어디서든 접근이 가능하다 - 전역 객체
  2. 브라우저의 창을 의미, 창을 제어하는 다양한 메서드를 제공
  3. window는 그냥 생략이 가능한 특징이 있다.

let, const 생성 변수 = 블록 스코프

console.clear() // 콘솔창 청소해줌
console.dir() // 가지고 있는 요소 ( 점으로 찍어서 접근할 수 있는 요소 )를 보여줌
console.log() // 콘솔창에 출력
console.table(data) // date를 테이블로 보여줌
console.group('one') console.group('two')
console.error('에러발생')
console.warn('경고발생')
console.info('정보')

typeof가 정확하게 나오긴 하지만 우리가 원하는 값이 아닐 수도 있다.

아래의 함수를 만들어 사용하는게 좀 더 정확하다.

function typeCheck(value) {
            const return_value = Object.prototype.toString.call(value);
            const type = return_value.substring(
                return_value.indexOf(" ") + 1,
                return_value.indexOf("]")
            );
            return type.toLowerCase();
        }

원시타입 : string, number, bigint, boolean, undefined, symbol, null

원시타입 vs 참조타입

  • 원시 타입 : 정수, 실수, 문자, 논리 리터럴등의 실제 데이터 값을 저장하는 타입
    • ex) boolean, char, byte, short, int, long, float, double
  • 참조 타입 : 객체의 번지를 참조하는 타입으로 메모리 번지 값을 통해 객체를 참조하는 타입
    • ex) 문자열, 배열, 열거, 클래스, 인터페이스, 정규표현식
    • 실제 객체는 힙 영역에 저장되며 참조 타입 변수는 스택 영역에 실제 객체들의 주소를 저장하여 객체를 사용할때마다 참조 변수에 저장된 객체의 주소를 불러와 사용하는 방식

함수들

s.length : s문자열의 길이를 알려줌
s.toUpperCase() : s의 모든 문자들을 대문자로 바꿔줌
s.toLowerCase() : s의 모든 문자들을 소문자로 바꿔줌

특정 문자 위치 찾기


//안에 들어있는지 찾는 함수
s.indexOf('특정문자') : 특정문자의 제일 앞 위치를 알려줌
s.indexOf('특정문자', num) : num번째 이후의 특정문자 위치를 알려줌
ex)
let text = "hi hello"
text.indexOf('h') // 0
text.indexOf('h',1)  // 3
s.search('특정문자') : 동일
//indexOf는 정규표현식 사용 불가
ex)
text.search('h') // 0

문자열 특정부분 잘라내기

//문자열 특정부분 잘라내기
//시작인덱스부터 종료 인덱스 바로 전까지 잘라냄
slice(시작인덱스, 종료인덱스)
ex)
let text = 'Hi my name is MinJu Kang'
text.slice(14,19) //MinJu
text.slice(19,14) //MinJu

//시작인덱스가 종료인덱스보다 높으면 빈 문자열 나옴
//시작인덱스부터 종료 인덱스 바로 직전까지 잘라냄
substring(시작인덱스, 종료인덱스)
//slice와 비슷
ex)
let text = 'Hi my name is MinJu Kang'
text.substring(14,19) //MinJu
text.substring(19,14) //MinJu

slice vs substring

  1. slice는 음수도 취급하지만 substring은 양수만 취급한다.
  2. 시작인덱스가 종료인덱스보다 클 경우 : substring은 두 값을 바꿔 실행한다. slice는 빈 문자열을(’’) 출력한다.

replace, replaceAll

부분 단어를 다른 단어로 바꿔준다.

s.replace('바꾸고싶은문자','바꿀문자')
s.replaceAll('바꾸고싶은문자','바꿀문자')
ex)
let text1 = 'Kang MinJu'
text1.replace('Kang','Kim')//'Kim MinJu'
let text2 = 'banana'
text2.replaceAll('na','ha')//'bahaha'

includes

포함하고 있는지 확인하고 true or false를 반환해준다.

s.includes('확인할 문자') //true or false
ex)
let text = 'Kang MinJu'
text.includes('Min') //true
text.includes('Man') //false

split

특정 문자나 공백을 기준으로 잘라 배열을 만들어 줌

s.split('특정문자나 공백')
ex)
let text = '010-1234-5678'
text.split('-') // [010,1234,5678]

trim

문자열 양끝의 공백을 없애준다.

s.trim()
ex)
let text = '   aa bb cc dd   '
text.trim() // 'aa bb cc dd'

padStart

문자열의 남은 크기에 원하는 문자를 넣어서 크기를 맞춰줌

s.padStart(원하는문자열크기,'넣고싶은문자')
ex)
let text = '123'
text.padStart(5,'0') // '00123'

concat

기존의 문자열에 새로운 문자열을 추가시킨다.

s.concat(p)
ex)
let text1 = 'hi'
let text2 = 'hello'
text1.concat(text2) // 'hihello'

산술연산

모든 프로그래밍 언어의 공통사항

부동소숫점 연산은 정확하지 않다.

2진수로 바꾸었을 때 무한대수가 발생하기 때문이다.

+ , - , / , * , ** , %
ex)
console.log(`10 + 3 = ${10 + 3}`)  // 10 + 3 = 13
console.log(`10 - 3 = ${10 - 3}`)  // 10 - 3 = 7
console.log(`10 / 3 = ${10 / 3}`)  // 10 / 3 = 3.333333333
console.log(`10 * 3 = ${10 * 3}`)  // 10 * 3 = 30
console.log(`10 ** 3 = ${10 ** 3}`) // 10의 3승  // 10 ** 3 = 1000
console.log(`4 ** 0.5 = ${4 ** 0.5}`) // 4의 제곱근  // 4 ** 0.5 = 2
console.log(`10 % 3 = ${10 % 3}`) // 나머지  // 10 % 3 = 1

연산자

// 단항연산
console.log(-2)       // -2
console.log(-(-2))    // +2
// console.log(--2)   // error
console.log(+4)       // 4
console.log(+'4')     // 4
// 소숫점 제거
console.log(~~3.14)   // 3

증감연산자

let num = 3;
console.log("증감연산 : ", ++num);    //  4
console.log("증감연산 : ", num++);    //  5
console.log("증감연산 : ", --num);    //  4
console.log("증감연산 : ", num--);    //  3

console.log("비교연산 : ", 2 > 3);    //  false
console.log("비교연산 : ", 2 >= 3);   //  false
console.log("비교연산 : ", 2 < 3);    //  true
console.log("비교연산 : ", 2 <= 3);   //  true
console.log("비교연산 : ", 2 == 3);   //  false
console.log("비교연산 : ", 2 != 3);   //  true
console.log("비교연산 : ", 2 === 3);  //  false
console.log("비교연산 : ", 2 !== 3);  //  true

숫자를 표현하는 여러가지 기법

parseInt("123"); // 123
parseInt("123.123"); // 123
parseInt("123px"); // 123
parseInt("px123"); // NaN
parseInt('     10'); // 10
parseFloat("123.123"); // 123.123
parseFloat("123.123px"); // 123.123
parseFloat("px123.123"); // NaN
parseInt('11', 2); // 3  ( 2진법 )
parseInt('11', 10); // 11  ( 십진법 )

isNaN 보다는 Number.isNaN을 권고

Number.isNaN(NaN);     //true
Number.isNaN(10);      //false
Number.isNaN("10");    //false
Number.isNaN("10px");  //false
Number.isNaN([]);      //false
Number.isNaN({});      //true

Math

Math.PI; // 3.141592653589793
Math.round(10.49); // 10
Math.round(10.77); // 11
Math.abs(-10); // 10
Math.pow(2, 3); // 8, 2**3
Math.pow(4, 0.5); // 2
Math.sqrt(16); // 4, 16**0.5
Math.random(); // 0 ~ 1 사이의 랜덤한 숫자
Math.ceil(10.1); // 11
Math.floor(10.9); // 10
Math.max(1, 2, 3, 4, 5); // 5
Math.min(1, 2, 3, 4, 5); // 1

Boolean

console.log(true && true)         //true
console.log(true && false)        //false
console.log(false && true)        //false
console.log(false && false)       //false
//심화과정      
console.log('가' && '나')         //'나'
console.log('' && '나')           //''

// or(논리합)
console.log(true || true)     //true
console.log(true || false)    //true
console.log(false || true)	  //true
console.log(false || false)   //false
// 어려운 내용
let username = 'leehojun'
console.log(username || '이름없음')

let username = ''
console.log(username || '이름없음')

console.log('가' && '나') // '나' 출력, '나'는 true로 평가
console.log(0 && -1) // 0
console.log(0 && 1) // 0
console.log(1 && 1) // 1
console.log(1 && '안녕') // '안녕'
console.log(1 && true) // true
console.log(0 || true) // true
console.log(1 && '안녕') // '안녕'
profile
나의 기억저장소

1개의 댓글

comment-user-thumbnail
2023년 8월 5일

유익한 자료 감사합니다.

답글 달기