String이라는 전역객체는 문자열(문자의 나열)의 생성자
리터럴 : 기호를 통해 손쉽게 객체 데이터 생성 ( {}, [])
String : 전역객체별로 생성해줘야함 (귀찮)
String통해 동작시킬 수 있는 명령
string.prototye
string.prototype.indexOf() // 찾을 수 없으면 -1반환 string.length string.slice(0,3) // index 0부터 index 2까지 string.replace('world', 'hi') *정규표현식사용* string.match(/.+(?=@)/)[0] // @이후 지우고 아이디만 반환 string.trim() // 공백 모두 삭제
1) 숫자
num.toFixed(2) // 소수점 두자리 이후 제외 문자열로 리턴 parseInt(num) // int로 변경하는 전역함수 parseFloat(num) // float으로 변경하는 전역함수
2) 수학 (math 객체)
수학적인 상수와 함수를 위한 속성과 메서드를 가진 내장 함수 (함수 객체 아님)
Math.abs(-1) Math.min(2, 8) Math.max(2, 8) Math.ceil(3.14) // 올림 Math.floor(3.14) // 내림 Math.round(3.14) // 반올림 Math.random() // 0.무작위 여러 숫자
const numbers = [1,2,3,4] const fruits = ['Apple', 'Banana', 'Cherry'] numbers[1]
array.length array.find(element => element > 10) // 없으면 undefined 반환
array.concat(fruits) // 두 개의 배열데이터 병합 (원본손상X)
array.forEach(function (element, index, array) { console.log(element, index, array) }) array.map(function (element, index, array) { return `${fruit} - ${index}` })
const b = fruit.map(function (fruit, index) { return { id: index, name: fruit } }
array.map(number => { return number <3 // 콜백실행 }) 결과 : true true false false ---------- array.map(number => { return number <3 // 콜백실행 }) 결과 : 1, 2 (필터링한 결과 반환)
축약
const a = numbers.map(number => number <3) const b = numbers.filter(number => number <3)
find
const a = fruits.find(fruit => { return /^B/.test(fruit) // 정규표현식 // B로 ^시작하는 문자데이터 }) 찾으면 반복 중지되고 찾아진 아이템 반환
findIndex
const a = fruits.findIndex(fruit => { return /^B/.test(fruit) }) 찾으면 인덱스 번호 반환
축약
const a = fruits.findIndex(fruit => /^C/.test(fruit))
include
array.includes(3) O : true X : false
(원본 수정됨)
array.push(5) // 배열 마지막 인덱스 뒤 데이터 삽입 array.unshift(0) // 배열 가장 앞쪽 데이터 삽입 array.reverse() // 뒤집어짐 array.splice(2,1) (인덱스, 개수) // 해당 인덱스 값부터 개수만큼 값 삭제 array.splice(2,0,999) // 해당 인덱스에 지우지말고 값추가
prototype (X)
static method (정적 메소드)
Object.assign()
const target = { a:1, b:2 } const source = { b:3, c:4 } const returnTarget = Object.assign(target, source) // 객체 합쳐서 출력 'b'속성 중복되기 때문에 b:3
returnTarget === target // true const a = {k:123}, const b = K:123} a === b // false
왜? - 참조형데이터이기 때문 (객체, 배열, 함수)
새로운 객체데이터를 만들고 싶다면?
const returnTarget = Object.assign({},target, source)
Object.keys
const keys = Object.keys(user) // property(key)만 추출 (name, age, email) const keys = Object.keys(user)
인덱싱
user['email'] -> value 출력 const values = keys.map(key => user[key]) // value 끄집어내는 것 가능
== 비구조화 할당
객체 데이터 property 꺼내서 사용
const {name, age, email, address} = user 객체 내에 없다면 undefined user.email 식으로도 가능
나중에 사용할거라면 기본값 할당 & 변수이름 변경해서 사용하려면 콜론
const {name: hello, age, email, address = 'Korea'} = user
배열인 경우 구조분해할당할때 []
const[,b] = frutis // 두번째 가져오고싶을때 쉼표로 둬야함
배열 console.log(...fruits) // 배열 내용(아이템) 출력 = fruits[0], fruits[1], fruits[0] (a,b, ...c) // 나머지
속성이름과 변수(데이터)이름 같으면 하나만남겨둬도됨
a: a -> a
원시데이터
: String, Number, Boolean, undefiend, null
참조형데이터
: Object, Array, Function
원시데이터의 불변성
원시데이터를 사용했을때 기존 메모리주소에 들어있다면 새롭게 만드는 것이 아니라 기존 메모리주소를 바라보도록 하는 것
참조형데이터의 가변성
객체 데이터 각각 다른 메모리를 바라봄
한쪽 수정하면 다른 한쪽에서 값이 수정된 상태로 나옴
->참조형 데이터를 할당할 때 구분에서 관리하고 싶을때
얕은복사(shallow copy)
: 표면만 복사
깊은복사(deep copy)
: 내부 모든 관계 참조까지 새로운 메모리로 복사
const user = { name: 'hello', age: 33, emails: ['aaaa@gmail.com'] } const copyUser = user // 같은 메모리주소 바라봄 user.age = 22 //
얕은 복사
const copyUser = Object.assign({}, user) // 정적메소드 const copyUser = {...user} // 전개 연산자
user.emails.push('asdfas@lins.com') user.emails === copyUser.emails //true //참조형 데이터인 배열 복사하지 않음
깊은복사
npm i lodash import _(객체데이터, 로대쉬기능) from 'lodash'
_.cloneDeep(user)