우리는 이미 앞서 타입, 배열, 객체 등을 통해 다양한 자료형이 있음을 배웠습니다.
이러한 자료형을 기반으로 해당 데이터를 조작하는 함수를 특별히 메소드(Method)라고 부릅니다.
이번 데이터 다루기 시리즈는, 문자열/배열/숫자의 메소드를 통해 각 자료형을 다루는 방법에 대해 알아봅니다.
특별히 배열의 메소드를 통해 불변성과 함수형 프로그래밍을 다룹니다. 낯선 용어가 또 등장하는 것이 두려우신가요? 용어 그 자체에 대해 너무 집착하지 않았으면 좋겠습니다. 굳이 한마디로 정의하지 않아도 됩니다. 그저 각 Lesson을 따라가면서 자연스럽게 메소드의 특징을 이해하고, 어떤 때에 자료형이 변하지 않는지 이해하고, 왜 함수형 프로그래밍이라고 불리는지를 이해하시기 바랍니다.
Achievement Goals
- 문자열과 숫자를 메소드를 이용해 원하는 형태로 만들 수 있다.
- 메소드를 이용해 배열과 객체를 구분할 수 있다.
- 객체의 키 및 값의 존재여부를 확인할 수 있다.
- 배열의 앞/뒤에 element를 추가 또는 삭제할 수 있다.
- 불변성의 의미를 이해하고, 어떤 메소드가 Mutable/Immutable 한지 알수 있다.
- for문을 대체하여, forEach, map, filter, reduce, slice 등의 메소드를 이용해 배열을 원하는 형태로 만들 수 있다.
- 불변성을 유지하는 것이 왜 좋은지 이해할 수 있다 (advanced)
- 함수형 프로그래밍의 특징을 이해할 수 있다
- 함수를 인자로 넘기는 방법에 대해 이해할 수 있다.
- 메소드의 인자로 익명 함수를 즉시 넘기는 방법에 대해 이해할 수 있다.
- callback 이라는 용어에 대해 이해할 수 있다. (advanced)
Lesson 문자열 다루기
STRING METHODS
Basic Usages
-accessing a character
- +/concat
Properties
-length
Methods
-indexOf,lastlndexOf (includes)
-split
-substring(slice)
-toLowerCase / toUpperCase
Methods(Learn yourself)
-trim
-matchs
-replace
Basic Usages - accessing a character
- str[index]
ex]
var str = 'CodeStates'
console.log(str[0]); // 'C'
console.log(str[4]); // 'S'
console.log(str[10]); // undefinded
index로 접근은 가능하지만 쓸 수는 없다 (read -only)
즉 문자열은 read only다!
str[0] = 'G';
console.log(str); // 'Codestates' not 'Godestates'
Concatenating strings
+연산자를 쓸 수 있음
string 타입과 다른 타입 사이에 + 연산자를 쓰면, string 형식으로 변환
(toString)
var str1 = 'code';
var str2 = '"States"
var str3 = '1';
console.log(str1 + str2); // 'CodeStates'
console.log(str3 + 7) ; // '17'
str1.concat(str2,str3....); 의 형태로도 사용 가능
str1과 2,3를 다 더하는 그런 매소드다
굳이 쓸 필요없이 + 연산자로 충분하다.
ex
'1' + true // "1true"
'1' + 5 // "15"
'1' + [1,2,3]
"11,2,3"
length property - 문자열의 전체 길이를 반환
var str = 'CodeStates'
console.log(str.length); // 10
str.indexOf(searchvalue) str.메소드이름(넣어야할 내용들 = arguments들)
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 - 많이 쓴다
see more: str.includes(searchValue)
실무에서 실제도 쓸수도 있다.
느낌이 오시죠 ? true of false 입혀준다.
- Internet Explorer와 같은 구형 브라우저에서는 작동하지 않으므로 주의
str.split(seperator)
-arguments : 분리 기준이 될 문자열
-return value : 분리된 문자열이 포함된 배열
var str = 'Hello from the other side';
console.log(str.split(' ')); <- 빈스트링에 공백있다!
// [ 'Hello', 'from','the', 'other', 'side']
csv 형식을 처리할 때 유용
csv = comma seperator value - execel 쓰는 사람 익숙할것이다
let csv = '연도,제조사,모델,설명,가격
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00
csv.split(',')
scv.split('/n')
let lines = csv.split('/n' )등 사용 가능
let lines[1].split(',');
lines[0] 등
str.substring(start, end)
arguments : 시작 index, 끝 index
return value : 시작과 끝 index 사이의 문자열
var 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', index 범위
see more : str.slice(start, end)
substring 과 비슷하나, 몇가지 차이점을 보임
텍스트에 중간에 쏙 빼가지고 오고 싶을때 사용한다
str.toLowerCase() / str.toUpperCase() IMMUTABLE
arguments : 없음
return value: 대,소문자로 변환된 문자열
console.log('ALPHABET'.toLowerCase()); // 'alphabet'
console.log('alphabet'.toUpperCase()); // 'ALPHABET'
재미있는 사실 하나!
let word = 'hello';
word.toUppercase()
"HELLO"
word
"hello"
안바뀐 이유는 ? 초록색에 IMMUTABLE = 원본이 변하지 않는다는 것을 기억해라!
What is IMMUTABLE?
모든 string method는 immutable
즉, 원본이 변하지 않음
array method는 immutable 및 mutable 여부를 잘 기억해야 함
ex]
'blue whale'.substring(0,4) // "blue"
변수로 있을 수 있잔하요
새로운 값을 리턴할뿐이다.
var str = 'blue whale'
str.substring(0,4)
"blue"
str
"blue whale"
스트링에 있는 메소드는 원본을 건들이지 않는다!!
그래서 세로 대입해줘야한다
str = str.substring(0,4) // "blue"
str // "blue"
str = str.toUpperCase()
"BLUE"
str // "BLUE
그밖
learn yourself
trim
공백 문자 : 탭문자 (\t), Carrige return(\r\n) 및 return 문자(\n)
match(advanced)
replace(advanced)
정규 표현식 (advanced)
'Codestates > 06.15 - 07.10' 카테고리의 다른 글
2020.06.19 [⭐️TIL] 배열로 함수열 프로그래밍하기 (0) | 2020.06.20 |
---|---|
2020.06.18 [TIL] 배열 다루기 - 불변성 유지하기 (0) | 2020.06.18 |
2020.06.18 [TIL] 객체 (0) | 2020.06.18 |
2020.06.17 [⭐️TIL] 배열과 반복문 (0) | 2020.06.17 |
2020.06.16 [TIL] 에러메세지 보는 방법 (0) | 2020.06.17 |