22.04.27 string, array

beomhak lee·2022년 4월 27일

javascript

목록 보기
6/12
post-thumbnail

string

몇번째에 해당글자가 있는지 추출

const str = 'Hello world!'
console.log(str.indexOf('world'))

0번째부터 3번째까지 단어 추출

const str = 'Hello world!'
console.log(str.slice(0, 3))

'world' 를 'beom' 으로 바꿔줌

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

정규표현식으로 원하는 정보를추출가능

const str = 'beomhak@gmail.com'
console.log(str.match(/.+(?=@)/)[0])

공백제거

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

parseInt()
parseFloat()

const pi = 3.1456789456
const integer = parseInt(pi) // 숫자로변형해주고 정수만 반환
const float = parseFloat(pi) // 숫자로변형해주고 소수점까지 반환

Math

console.log ('abs: ', Math.abs(-12)) // 절대값 반환 12출력
console.log ('min: ', Math.min(2, 8)) // 작은값  2 반환
console.log ('max: ', Math.max(2, 8)) // 큰값  8 반환
console.log ('ceil: ', Math.ceil(3.14)) // 올림처리 4 반환
console.log ('floor: ', Math.floor(3.14)) // 내림처리 3 반환
console.log ('round: ', Math.round(3.14)) // 반올림처리 3 반환
console.log ('random: ', Math.random()) // 임의의값 반환

배열

sample

const numbers = [1,2,3,4]
const fruits = ['Apple', 'Banana', 'Cherry']

length

console.log(numbers.length) // 길이 (갯수) 4 반환 
console.log(fruits.length) // 길이 (갯수) 3 반환
console.log([1,2].length) // 길이 (갯수) 2 반환

contact()

console.log(numbers.concat(fruits)) // 원본 수정없이 배열이 합쳐진 새로운 배열 생김
//결과
0: 1
1: 2
2: 3
3: 4
4: "Apple"
5: "Banana"
6: "Cherry"

forEach()
배열데이터 아이템 갯수만큼 반복적으로 실행되는 함수

fruits.forEach((fruit, i) =>{
				console.log(fruit, i)
			})
//결과
Apple 0
Banana 1
cherry 2

map()
forEach 와 다르게 새로운 배열을 반환해준다.

const b = fruits.map((fruit, index) =>({
					 id:index,
					 name:fruit
				}))
console.log(b)

//결과
0: {id: 0, name: 'Apple'}
1: {id: 1, name: 'Banana'}
2: {id: 2, name: 'Cherry'}

filter()
특정한 내용만 필터링해서 출력 해준다. 원본에 영향은 주지않는다.

 const b = numbers.filter(number => number <3)
 console.log(b)

//결과
0: 1
1: 2

find() findIndex()
해당하는 요소를 찾아서 반환해준다.

const a = fruits.find(fruit => /^C/.test(fruit))
console.log(a)

//결과 
Cherry

const b = fruits.findIndex(fruit => /^C/.test(fruit))
			console.log(b)

//결과
2

includes()
포함되있는지 확인여부에따라 true false로 반환

const a = number.includes(3)
console.log(a)

const b = number.includes('strow')
console.log(b)

push()
배열의 뒤쪽에 데이터 삽입

numbers.push(5)

//결과
0: 1
1: 2
2: 3
3: 4
4: 5

unshift()
배열의 맨앞쪽에 데이터 삽입

numbers.unshift(0)

//결과
0: 0
1: 1
2: 2
3: 3
4: 4

reverse()
배열의 순서를 뒤집어준다.
(원본 수정됨 주의!)

numbers.reverse()

//결과
0: 4
1: 3
2: 2
3: 1

splice()
원본 수정됨 주의!

인덱스 2번째 값을 1개 제거
number.splice(2, 1)

인덱스 2번째 값을 1개 제거후 그자리에 99삽입
number.splice(2, 1, 99)

전개 연산자 (Spread)

마침표 세개로 출력을 하게되면 문자로 출력이 된다.

const fruits = ['Apple','Banana','Cherry','Orange']
console.log(fruits)
console.log(...fruits) // Apple Banana Cherry Orange

const toObject = (a, b, c) => ({a,b,c})

객체데이터로 변환을 해주면 
마침표세개를 찍으면 객체로 출력이된다.

console.log(toObject(...fruits))

//결과 
a: "Apple"
b: "Banana"
c: "Cherry"

0개의 댓글