JS 조건문과 문자열 6/27

waymo·2022년 6월 27일
0
post-thumbnail

💻 Unit3

1. 조건문

조건문 Conditional statement

  • 조건문은 어떠한 조건을 판별하는 기준을 만드는 것
  • 조건문에는 반드시 비교 연산자(comparison operator)가 필요
  • 조건문(conditional statement)은 주어진 조건식(conditional expression)의 평가 결과에 따라 코드 블럭의 실행을 결정

🔎비교 연산자

> < >= <= === !==

🟡조건문

if (조건) {
  // 조건이 참이면 이 코드 블록이 실행
} else {
  // 조건식이 거짓이면 이 코드 블록이 실행
}
  • 조건문의 평가 결과가 true일 경우 if 중괄호 안에 있는 코드가 실행되고 ,
    false일 경우 else 중괄호 안에 있는 코드가 실행된다.

if (조건1) {
  
} else if (조건2) {
  
} else {
  
}
  • else if를 사용하여 여러번 조건을 추가할 수 있다.

두가지 조건이 한번에 적용되는 경우
논리 연산자(Logical Operator)를 사용

💡논리 연산자(Logical Operaotr)

논리 연산자는 우항과 좌항의 피연산자를 논리 연산한다.
부정논리 연산자의 경우, 우항의 피연산자를 논리 연산한다.

! NOT 연산자 truthy,falsy 여부를 반전시킴

&& 논리곱(AND) 연산자

true && true // true
true && false // false
false && false // false

논리곱 연산자 &&는 두개의 피연산자가 모두 true로 평가될 때 true를 반환한다.

undefined && 10 // undefined
5 && false // false

// AND 연산자는 falsy한 값을 만나면, 그값을 출력
// 둘다 truthy할 경우 , 뒤에 있는 값을 출력

|| 논리합(OR) 연산자

true || true // true
true || false // true
false || false // false
undefined || 10 // 10
5 || 10 // 5
5 || console.log('실행되지 않음') // 5

// OR 연산자는 truthy한 값을 만나면 , 그값을 출력
// 둘다 falsy 할 경우 , 뒤에 있는 값을 출력

논리합 연산자||는 두개의 피연산자 중 하나만 true로 평가되어도 true로 반환한다

!false // true
!(3>2) // false
!undefined // true
!'Hello' // false

'Hello'를 true로 취급(truthy)
undefined를 false로 취급(falsy)
null undefined 0 NaN '' false


2. 문자열 (String Method)

IMMUTABLE

  • 모든 string method는 immutable
  • 즉 , 원본이 변하지 않음
  • array method는 immutable 및 mutable여부를 잘 기억해야함

문자열
문자열은 기본적으로 텍스트 정보이다 ' "를 사용하여 문자를 묶어 입력한다

1. str[index]

let str = "CodeStates'
console.log(str[0]); // 'C'
console.log(str[4]); // 'S'
console.log(str[10]); // undefined

// read-only

문자열 안에 모든 문자는 관련된 숫자에 상응한다
Each character has a corresponding index


2. 문자 접합 Concatenating Strings

  • 문자열은 + 연산자를 사용하여 접합 할수 있다
  • string 타입과 다른 타입 사이에 + 연산자를 쓰면, string형식으로 변환 (toString)
var str1 = 'Code';
var str2 = "States";
var str3 = '1';
console.log(str1 + str2); // 'CodeStates'
console.log(str3 + 7);   // '17'

3. length PROPERTY

.length

  • 문자열의 전체 길이를 반환
let str = 'Codestates';
console.log(str.length); // 10

4. str.indexOf(searchValue)

.indexOf()

문자열에서 주어진 인수가 나타나는 문자열 인덱스와 그 자릿수를 반환

  • arguments : 찾고자 하는 문자열
  • return value : 처음으로 일치하는 index, 찾고자 하는 문자열이 없으면 -1
  • lastIndexOf는 문자열 뒤에서 부터 찾음
'Blue Whale' .indexOf('Blue');          // 0
'Blue Whale' .indexOf('blue');         // -1
'Blue Whale' .indexOf('Whale');        // 5
'Blue Whale Whale' .indexOf('Whale');  // 5

'canal' .lastIndexOf('a');  //3
  • str.inclues(searchValue) 의 경우 string값에서 value값이 있는지 없는지 판별후 Boolean값으로 리턴

5. str.split(seperator)

split()

  • arguments : 분리 기준이 될 문자열
  • return value : 분리된 문자열이 포함된 배열
let str = 'Hello from the other side';
console.log(str.split(' '));
// ['Hello', 'from', 'the', 'other', 'side']
  • csv 형식을 처리할 때 유용
    csv 형식 처리할 때 줄바꿈(\n)부터 분리후 ','분리

6. str.substring(start, end)

substring

  • arguments : 시작 index, 끝 index
  • return value : 시작과 끝 index 사이의 문자열
let str = 'abcdefghij';
console.log(str.substring(0, 3));   // 'abc'
console.log(str.substring(3, 0));   // 'abc'
console.log(str.substring(1, 4));   // 'bcd'
console.log(str.substring(-1, 4));  // 'abcd', 음수는 0으로 취급
console.log(str.substring(0, 20));  // 'abcdefghij' 

텍스트의 원하는 범위를 추출하고 싶을때 사용!


7. str.toLowerCase() / str.toUpperCase()

toLowerCase()
대문자를 소문자로 리턴
toUpperCase()
소문자를 대문자로 리턴

  • arguments : 없음
  • return value : 대,소문자로 변한된 문자열
console.log('ALPHABET' .toLowerCase());   // 'alphabet'
console.log('alphabet' .toUpperCase());   // 'ALPHABET'

8 str.trim()

trim()
문자열의 처음과 끝에 오는 공백을 전부 깍아내어 준다

let greeting = '      leave me alone plz    ';

greeting.trim() // 'leave me alone plz'

사용자의 입력을 수용할 때 유용하고 문자열의 핵심만 뽑고 싶을 경우에 사용한다!

9. str.slice()

slice()
문자열의 일부를 추출하거나 잘라내서는 그 부분을 새로운 문자열로 반환해준다


let str = 'supercalifragil'

str.slice(0,5); // 'super' 0에서 5까지 추출

str.slice(5); // 'califragil' 5까지 잘라서 추출

음수일 경우 뒤에서 부터 시작

10. str.replace()

replace()

두 개의 인수를 받아서 교체되어야 할 값 , 그자리를 교체해서 들어가려는 값을 이용해 문자열을 바꿔준다.

  • 정규 표현식이라는 걸 이용해서 패턴에 매칭시켜서 특정한 문자열 대신에 패턴을 교체할 수도 있다( 정규표현식도 배우고 다른것도 더 배우고 시도해봐야 겠다)

let msg = "haha that is so funny!"

msg.replace('haha', 'lol') 
// "lol that is so funny!"
  • 교체되어야 할 인수가 문자열에 여러개가 있을 경우 제일 첫 번째 글자에만 적용된다.

11. Template Literals

`I counted ${3 + 4} sheep`; // "I counted 7 sheep"
  • 문자열 안에 표현식을 내장할 수 있는 문자열들을 만들고 해당 표현식은 평가된 후에 문자열로 바뀐다
  • 템플릿 리터럴 에는 ``백틱(back-tick) 기호를 사용한다.


MATH OBJECT

Math 객체

1. 내림

Math.floor

2. 올림

Math.ceil

3. 랜덤

Math.random

0과 1사이의 소숫점 사이의 숫자를 임의로 생성

4. 반올림

Math.round()

Math.round(4.9) // 5

5. 절댓값

Math.abs()

Math.abs(-456) // 456

6. 파워

Math.pow()
제곱

Math.pow(2,5) // 32

2 ** 5 // 32
profile
FE 개발자(진)가 되고 싶습니다

0개의 댓글