const result = 'hello world!'.indexOf('Heropy')
console.log(result); // -1 출력
const str = '0123'
console.log(str.length) // 4 출력
const str1 = 'hello world'
console.log(str1.indexOf('heropy') !== -1) // false 출력
console.log(str1.slice(0, 3)) // hel 출력
console.log(str1.replace('world', 'heropy')) // hello heropy 출력
console.log(str1.replace(' world', '')) // hello 출력
const str2 = 'yuh2201@gmail.com'
console.log(str2.match(/.+(?=@)/)[0]) // 정규표현식, yuh2201 출력
const str3 = ' hello world '
console.log(str3) // 공백 존재하는 상태로 출력
console.log(str3.trim()) // 앞 뒤의 공백들이 사라진 상태로 출력
const pi = 3.14159265358979
console.log(pi)
const str = pi.toFixed(2) // 소수점 몇자리까지 보여질 것인지,나머지는 제거
console.log(str) // 3.14 출력
console.log(typeof str) // string 출력
const integer = parseInt(str) // 3 출력
const float = parseFloat(str) // 3.14 출력
console.log(integer)
console.log(float)
console.log(typeof integer, typeof float)
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()) // 랜덤한 숫자를 반환하게 됨, 새로고침 시 계속 다른 수 출력, 난수
const numbers = [1,2,3,4]
const fruits = ['apple', 'banana', 'cherry']
console.log(numbers[1]) // 2 출력
console.log(fruits[2]) // cherry 출력
.length
console.log(numbers.length) // 4 출력
console.log(fruits.length) // 3 출력
console.log([1, 2].length) // 2 출력
console.log([].length) // 0 출력 : 빈 배열
.concat
console.log(numbers.concat(fruits)) // [1, 2, 3, 4, 'apple', 'banana', 'cherry'] 출력
console.log(numbers) // [1, 2, 3, 4]
console.log(fruits) // ['apple', 'banana', 'cherry']
.forEach
메소드가 붙은 배열 데이터의 아이템 갯수만큼 콜백 함수가 반복이 됨, 따로 반환되는 값은 없음
apple 0 (3) ['apple', 'banana', 'cherry']
banana 1 (3) ['apple', 'banana', 'cherry']
cherry 2 (3) ['apple', 'banana', 'cherry'] 로 출력
fruits.forEach(function(element, index, array){
console.log(element, index, array)
})
/*
화살표 함수!
fruits.forEach((element, index, array) => {
console.log(element, index, array)
})
*/
! element 대신 item 으로도 많이 사용함, array 는 사용 잘 안함
fruits.forEach(function(item, i){
console.log(item, i)
})
.map
내부의 콜백에서 반환된 특정한 데이터를 기준으로 데이터들의 새로운 배열을 메소드가 실행된 자리에서 반환 됨
const a = fruits.forEach(function(fruit, index){
console.log(`${fruit} - ${index}`)
/*
apple - 0
banana - 1
cherry - 2 출력
*/
})
console.log(a) // undefined 출력
const b = fruits.map(function(fruit, index){
return `${fruit} - ${index}` // 리턴 키워드 사용
})
console.log(b) // (3) ['apple - 0', 'banana - 1', 'cherry -2']출력
/*
하나의 데이터를 가지고 그 데이터를 모아둔 새 배열을 가지고 반환 함
0 : "apple - 0"
1 : "banana - 1"
2 : "cherry - 2"
*/
const c = fruits.map(function(fruit, index){
return {
id: index,
name: fruit
}
})
console.log(c)
/*
(3) [{…}, {…}, {…}]
0: {id: 0, name: 'apple'}
1: {id: 1, name: 'banana'}
2: {id: 2, name: 'cherry'}
length: 3
[[Prototype]]: Array(0) 출력
*/
/*
화살표 함수!
const c = fruits.map((fruit, index) => ({
id: index,
name: fruit
}))
*/
.filter
const numbers = [1,2,3,4]
const fruits = ['Apple', 'Banana', 'Cherry']
const a = numbers.map(number => {
return number < 3
})
const a = numbers.map(number => number < 3)
! 배열 데이터의 갯수만큼 새롭게 반복된 배열 데이터 만들어짐
console.log(a) // [true, true, false, false] 출력
const b = numbers.filter(number => {
return number < 3
})
const b = numbers.filter(number => number < 3)
! 필터링을 한 후 일부 내용을 걷어내고 새로운 배열 데이터 만들어짐
! 원본의 갯수랑 다를 수 있음
console.log(b) // [1,2] 출력
! map, filter 둘다 원본데이터에 관계 없이 새로운 배열을 만드는 것
find, findIndex
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry']
const a = fruits.find(fruit => /^B/.test(fruit)
// 정규표현식 : 대문자 B로 시작하는 매개변수
)
! 내가 원하는 특정한 아이템을 찾아 반환하기
! 찾으면 반복 종료
console.log(a) // Banana 출력
const b = fruits.findIndex(fruit => /^C/.test(fruit))
console.log(b) // 2
! 몇변째에 존재하는지 숫자를 출력함
includes
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry']
const a = numbers.includes(3)
console.log(a) //true 출력
const b = fruits.includes('test')
console.log(b) // false 출력
! 인수로 사용되는 특정한 데에터가 특정한 배열에 들어있는지 들어있지 않은지 출력해주는 메소드
! .push(), .unshift()
// 원본 수정됨 주의!
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry']
numbers.push(5)
console.log(numbers) // [1,2,3,4,5] 출력
// 배열에 가장 뒤 쪽에 특정한 인수를 밀어 넣음
numbers.unshift(0)
console.log(numbers) // [0,1,2,3,4,5] 출력
// 배열에 가장 앞 쪽에 특정한 인수를 밀어 넣음
reverse
원본이 수정됨
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry']
numbers.reverse()
fruits.reverse()
console.log(numbers) // [4,3,2,1] 출력
console.log(fruits) // ['cherry', 'banana', 'apple'] 출력
// 배열의 아이템 순서를 뒤집어서 출력해주는 메소드
splice
원본이 수정됨
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry']
numbers.splice(2,1) // splice(배열의 인덱스 값, 인덱스 번호에서 아이템 몇개를 지울 것인지)
console.log(numbers) // [1,2,4] 츌력
numbers.splice(2,0) // 지울 아이템이 없기 때문에 그대로 출력
console.log(numbers) // [1, 2, 4] 출력
numbers.splice(2, 0, 999) // 그 자리에 세번째 인수 추가
console.log(numbers) // [1, 2, 999, 4] 출력
! 특정한 인덱스의 아이템을 제거 하는 용도,
! 새로운 아이템을 끼워넣는 용도로도 사용!
! 삭제와 끼워넣기 둘 다 가능
numbers.splice(2, 1, 99) // 두번째 자리에 있는 한개를 지우고 그 자리에 99 넣기
console.log(numbers) // [1, 2, 99, 4] 출력
fruits.splice(2, 0, 'Orange')
console.log(fruits) // ['apple', 'banana', 'orange', 'cherry'] 출력
const userAge = {
// key: value 형태
name: 'heropy',
age: 85
}
const userEmail = {
name: 'heropy',
email: 'thesecon@gmail.com'
}
const target = Object.assign(userAge, userEmail) // 대상객체, 출처객체
console.log(target) // {name: 'heropy', age: 85, email: thesecon@gmail.com}
console.log(userAge)// {name: 'heropy', age: 85, email: thesecon@gmail.com}
console.log(target === userAge) // true 출력, 타겟으로 속성의 값을 복사해서 집어넣으면 그 객제가 반환
const a = {k: 123}
const b = {k: 123}
console.log(a === b) // false 출력
! 생긴건 똑같지만 서로 다른 객체
! 자비스크립트의 불변성, 가변성과 연관
하나의 메모리 주소에 값이 들어가 있는데 메모리 주소에 있는 내용만 참고해서 사용하고 있음 (참조형 데이터) (target, userAge)
! a, b는 서로 다른 메모리 주소를 바라보고 있어서 false 출력됨
const target = Object.assign({}, userAge, userEmail)
// 앞에 {} 를 추가하면 새로운 배열을 만들어서 추가시켜줌
console.log(target) // {name: 'heropy', age: 85, email: thesecon@gmail.com}
console.log(userAge)// {name: 'heropy', age: 85}
console.log(target === userAge) // false 출력
const user = {
name: 'heropy',
age: 85,
email: 'thesecon@gmail.com'
}
const keys = Object.keys(user)
console.log(keys) // [name, age, email] 출력
// key들만 추출되어 배열데이터로 만들어진다
console.log(user['email']) //thesecon@gmail.com 출력
! 객체 데이터 인덱싱 방법
keys[인덱스번호]
keys[프로퍼티의 이름] 둘 다 출력 가능
const values = keys.map(key => user[key]) // 콜백함수 3번 실행
console.log(values) // ['heropy', 85, 'thesecon@gamil.com'] 출력
const user = {
name: 'heropy',
age: 85,
email: 'thesecon@gmail.com'
}
const {name, age, email, address, city = 'korea'} = user
// E.g, user.address
/*
user라는 배열을 구조분해해서
내가 원하는 내용을 변수로 만들어서 활용할 수 있는 것
*/
console.log(`사용자의 이름은 ${name}입니다.`)
console.log(`${name}의 나이는 ${age} 입니다.`)
console.log(address) // undefined
console.log(city) // 기본 값 할당 가능 (값이 없을 경우에 사용됨)
// user에 city의 값을 추가해두면 기본 값은 무시됨
const fruits = ['Apple', 'Banana', 'Cherry']
// const [a, b, c, d] = fruits
const [, , b] = fruits // 순서는 꼭 지켜주어야 함
console.log(b) // Apple Banana Cherry undefined 출력
const fruits = ['apple', 'banana', 'cherry', 'Orange']
console.log(fruits) // ['apple', 'banana', 'cherry']
console.log(...fruits) // apple banana cherry
function toObject(a, b, c){
return {
a: a,
b: b,
c: c
}
}
console.log(toObject(...fruits)) // {a: 'apple', b: 'banana', c: 'cherry'}
console.log(toObject(fruits[0], fruits[1], fruits[2])) {a: 'apple', b: 'banana', c: 'cherry'}
function toObject(a, b, ...c){
return {
a: a, // 속성의 이름과 변수에 이름이 같을 때 축약형으로 a만 남겨놓아도 됨
b: b,
c: c
}
}
축약
const toObject = (a, b, ...c) => ({a, b, c})
console.log(toObject(...fruits))
// {a: 'apple', b: 'banana', c: Array(2)} c: ['cherry', 'Orange']
데이터 불변성
원시 데이터: string, number, boolean, undefined, null
참조형 데이터: Object, Array, function
< 원시 데이터 : 모양이 같으면 같다고 표현이 된다 >
let a = 1
let b = 4
console.log(a, b, a === b) // 1 4 false
b = a // b에게 a의 메모리주소 할당
console.log(a, b, a === b) // 1 1 true
a = 7
console.log(a, b, a === b) // 7 1 false
let c = 1 // 기존 메모리 주소에 있는 1을 바라보게 됨
console.log(b, c, b === c) // 1 1 true, b도 1의 메모리를 c도 1의 메모리를 바라보게 됨
< 참조형 데이터 (가변) >
// 원시 데이터처럼 메모리 주소에 추가되는것이 아니라 선언될 때 마다 새로운 메모리 주소에 할당이 될 수 있음
// 한쪽이 수정되면 다른 한 쪽도 수정될수가 있음
let a = {k: 1}
let b = {k: 1}
console.log(a, b, a === b) // k: 1, k: 1, flase
a.k = 7
b = a // 완전히 다르게 하려면 복사를 해야함 (얕은 복사/깊은 복사)
console.log(a, b, a === b) // k: 7, k: 7, true
a.k = 2
console.log(a, b, a === b) // k: 2, k: 2, true
let c = b
console.log(a, b, c, a === c) // k: 2, k: 2, k: 2, true
a.k = 9
console.log(a, b, c, a === c) // k: 9, k: 9, k:9, true
import _ from 'lodash'
얕은 복사, 깊은 복사
const user = {
name: "heropy",
age: 85,
emails: ['thesecon@gmail.com']
}
// const copyUser = user
// console.log(copyUser === user) // true 출력
// user.age = 22
// console.log('user', user) // name: heropy, age: 22, emails: array(1)
// console.log('copyUser', copyUser) // name: heropy, age: 22, emails: array(1)
// // user의 age만 수정했는데 copyUser도 같이 변경됨 > user와 copyUser가 같은 메모리 주소를 보고 있음
///// 얕은 복사
// const copyUser = Object.assign({}, user)
// const copyUser = {...user}
// console.log(copyUser === user) // false 출력
// user.age = 22
// console.log('user', user) // name: heropy, ageL 22, email: array(1)
// console.log('copyUser', copyUser) // name: heropy, age: 85, email: array(1)
const copyUser = _.cloneDeep(user) // 복제, 깊은
console.log(copyUser === user) // false 출력
console.log('---------')
console.log('---------')
//// 깊은 복사
// 참조형 데이터로 들어가서 모든걸 복사처리 해주어야함
user.emails.push('neo@zillinks.com')
console.log(user.emails === copyUser.emails) // ture 출력
/*
user에 email은 하나의 메모리 주소를 공유함
*/
console.log('user', user) // emails 가 두개
console.log('copyUser', copyUser)// emails 가 두개(동일), age의 숫자는 다르지만 같은 email의 배열은 동일
가져오기, 내보내기
Json
- 자바스크립트를 표현하는 하나의 포맷, key-value 형태
- 자바스크립트의 객체 표기법
- 문자열에서는 큰 따움표만 지원함
import myData from './myDate.json'
console.log(myData)
/*하나의 json파일은 하나의 데이터 파일이기 때문에 여러개의 데이터를 사용할 수 없음*/
// undefined는 사용할 수 없음
const user = {
name: 'heropy',
age: 85,
emails: [
'thesecon@gmail.com',
'neo@zillinks.com'
]
}
console.log('user', user)
const str = JSON.stringify(user)
console.log('str', str)
console.log(typeof str) // string 출력
const obj = JSON.parse(str)
console.log('obj', obj)
console.log(typeof obj) // object 출력