JS LevelUp - Data

HunGeun·2022년 4월 28일
0

HTML_CSS_JS

목록 보기
10/11

데이터

- String

문자
String MDN

  • properties
    legnth
    example)
const str = 'Hello';

console.log(`${str} ${str.length}`);
//output: Hello 5
  • methods
    example)
//indexOf
const result = 'Hello world'.indexOf('world')
			 // String.prototype.indexOf()
console.log(result) //6

--------------------------------------------------
const str = '0123'

console.log(str) //0123
console.log(str.length) //4

--------------------------------------------------
const str = "hello world!"

console.log(str.indexOf('world')) //6
console.log(str.indexOf('abc')) //-1 존재하지 않으면 -1 출력
console.log(str.slice(0, 3)) // hel 0~2번째 
//beginIndex, endIndex: 0부터 시작하는 추출 종료점 인덱스 즉 그 직전까지 반환

console.log(str.replace('world', 'abc'))// hello abc!
console.log(str.replace(' world!', ''))// hello
--------------------------------------------------
const str = 'abc@gmail.com'
console.log(str.match(/.+(?=@)/)[0]); //abc 정규표현식 배열데이터 반환 및 0번째 출력
// abc
--------------------------------------------------
const str = '   Hello wolrd  '
console.log(str.trim()) //Hello wolrd 공백제거

이외에도 많은 methods 존재

math

  • 숫자와 수학
    내장 객체 math
    math MDN
    example)
const pi = 3.14159265358979
console.log(pi)

const str = pi.toFixed(2)
console.log(str) //3.14 
console.log(typeof str) //string
//toFix 사용시 str로 반환된다

const integer = parseInt(str) //parseInt는 전역함수, 정수화
const float = parseFloat(str) // 실수화
console.log(integer) //3
console.log(float) //3.14
console.log(typeof integer, typeof float) //number number

//methods
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('round: ', Math.round(3.5)) // 4 반올림
console.log('ramdom: ', Math.random()) //0~1랜덤 숫자 

Array

Array MDN
zero-base numbering

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

console.log(numbers[1]) // 2
console.log(fruits[2]) // Cherry

length

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

console.log(numbers.length) //4
console.log(fruits.length) //3
console.log([1,2].length) //2
console.log([].length) //0 length를 이용해서 배열이 비어있는지 확인 가능

concat

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

console.log(numbers.concat(fruits)) //[1, 2, 3, 4, 'Apple', 'Banana', 'Cherry']
console.log(numbers) // [1,2,3,4] concat를 사용해도 원본에는 영향 없음
console.log(fruits) //['Apple', 'Banana', 'Cherry'] concat를 사용해도 원본에는 영향 없음

forEach

  • 인수로 콜백을 사용하고, 배열데이터의 갯수만큼 실행함
    reeturn 값이 없기때문에 변수에 담을 수 없음
const numbers = [1,2,3,4]
const fruits = ['Apple', 'Banana', 'Cherry']

fruits.forEach(function (item, index, array) {
    console.log(item, index, array)
})
// Apple 0 (3) ['Apple', 'Banana', 'Cherry']
// Banana 1 (3) ['Apple', 'Banana', 'Cherry']
// Cherry 2 (3) ['Apple', 'Banana', 'Cherry']

//매개변수명 지정가능
fruits.forEach(function (fruits, i) {
    console.log(fruits, i)
})
// Apple 0
// Banana 1
// Cherry 2


//-> arrow
const a_arrow = fruits.forEach((fruit, index) => {
    console.log(`${fruit}-${index}`)
})
// Apple-0
// Banana-1
// Cherry-2
console.log(a) // undefiend 
//foreach는 return 값이 없기때문에 변수에 담을 수 없음

map

  • foreach와 비슷하지만 return값이 존재
  • 콜백에서 반환된 데이터로 생성된 배열을 return 함
const numbers = [1,2,3,4]
const fruits = ['Apple', 'Banana', 'Cherry']


const b = fruits.map(function (fruit, index) {
    return `${fruit}-${index}`
})

const b2 = fruits.map((fruit, index)  => ({
    id: index,
    name: fruit
}))
console.log(b) //['Apple-0', 'Banana-1', 'Cherry-2']
console.log(b2) 
//0: {id: 0, name: 'Apple'}
//1: {id: 1, name: 'Banana'}
//2: {id: 2, name: 'Cherry'}

filter

  • 배열데이터를 특정기준으로 filter함
    콜백에서 반환되는값이 true 인 데이터로만 배열생성
const numbers = [1,2,3,4]
const fruits = ['Apple', 'Banana', 'Cherry']

const a = numbers.map(number => number < 3)

const b = numbers.filter(number => number < 3) 
})
console.log(a) //[true, true, false, false]
console.log(b) // [1, 2]

find & findIndex

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

const a = fruits.find(fruit => {
    return /^B/.test(fruit) 
  	//정규표현식: 대문자B로 시작하는 문자데이터 true
    //또한 true가 나와서 찾으면 거기서 종료
})
console.log(a) //Banana

const b = fruits.findIndex(fruit => /^C/.test(fruit)) 
//정규표현식: 대문자C로 시작하는 데이터의 index값 return
//또한 찾으면 거기서 종료
})
console.log(b)// 1

includes

  • 포함 여부 boolean return
const numbers = [1,2,3,4]
const fruits = ['Apple', 'Banana', 'Cherry']

const a = numbers.includes(3)
console.log(a) //True

const b = numbers.includes(5)
console.log(b) //False

push, unshift reverse ,splice (!!원본수정)

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]

numbers.reverse() //배열 순서 뒤집기
console.log(numbers) //[5, 4, 3, 2, 1, 0]

numbers.splice(2,1) //2번 인덱스부터 1개를 지워라
console.log(numbers) // [5, 4, 2, 1, 0]
//-----------------------------------
const numbers2 = [1,2,3,4]
numbers2.splice(2,1,99)//2번 인덱스부터 1개를 지우고 99를 넣어라
console.log(numbers2) // [1, 2, 99, 4]

Object

Object MDN

static methods

  • 리터럴로 선언된 객체에 사용하지 못함

example)

//Object.assign

const userAge = {
    // key: value
    name: 'hun',
    age: 50
}
const userEmail = {
    name:'hun',
    email: 'abc@gmail.com'
}

const target = Object.assign(userAge, userEmail)
//source인 userEmail의 데이터를 target인 userAge로 복사
console.log(target)
// {name: 'hun', age: 50, email: 'abc@gmail.com'}
console.log(userAge)
//{name: 'hun', age: 50, email: 'abc@gmail.com'}
console.log(target === userAge)
//true assign 즉 할당했기때문에 메모리주소가 같기때문에 true가 나옴

const a = { k: 123 }
const b = { k: 123 }
console.log(a===b)
//false 
//다른 메모리 주소를 가지기 때문에 false

//원본 데이터를 보존하고, 두개의 객체를 합쳐서 완전히 새로운 객체를 만들고 싶다면 빈 객체를 만들어서 assign 한다
const newO = Object.assign({}, userAge, userEmail)

keys

  • key값으로 배열 생성
//keys
const user = {
    // key: value
    name: 'hun',
    age: 50,
    email: 'abc@gmail.com'
}

const keys = Object.keys(user)
console.log(keys) //['name', 'age', 'email']

console.log(user['email']) //abc@gmail.com
//key값으로 indexing이 가능하다

const values = keys.map(key => user[key])
//-->user[name], user[age], user[email] --> hun, 50, abc@gmail.com 로 배열 생성
console.log(values) //['hun', 50, 'abc@gmail.com']

Destructuring assignment

  • 구조 분해 할당 = 비구조화 할당
// Object destructuring assignment
const user = {
    name: 'hun',
    age: 50,
    email: 'abc@gmail.com'
}

const { name: aname, age, email, address } = user

console.log(`${name}`) //hun
console.log(`${age}`) //50
console.log(`${email}`) // abc@gmail.com
console.log(`${address}`) //undefined
// 구조 분해 할당시 undefined시 지정할 기본값 설정 가능
// ex) address = 'Korea'

//Array destructuring assignment
//순서대로 
const fruits = ['Apple', 'Banana', 'Cherry']
const [a, b, c, d ] = fruits
console.log(a,b,c,d) // Apple Banana Cherry undefined

//만약 특정 깂만 가져오고 싶다면
const [, , e] =fruits
console.log(e) // Cherry

Spread

  • 전개 연산자(...)
    매개변수 부분에 전개 연산자를 사용하면 나머지 인수가 배열데이터로 들어감 (rest parameter)
    속성이름과 변수(데이터의 이름)이 같다면 축약 가능 a: a, ---> a,
const fruits = ['Apple', 'Banana', 'Cherry']
console.log(fruits) //['Apple', 'Banana', 'Cherry']
console.log(...fruits)// Apple Banana Cherry 

function toObject(a,b,c) {
    return {
      a: a,
      b: b,
      c: c
   }
}
---> 간소화
const toObject = (a, b, c) => ({a, b, c})
console.log(toObject(...fruits)) //{a: 'Apple', b: 'Banana', c: 'Cherry'}

Immutability

데이터 불변성

  1. Primitive Type
    원시 데이터: String, Number, bool undefined, null... 불변성을 가짐
  2. Reference Type
    참조형 데이터: Object, Array, Function ...
//Primitive Type
let a = 1
let b = 4
console.log(a, b, a === b) //1, 4 fasle | a와 b가 바라보는 메모리 주소가 다르기 때문에 false

b = a
console.log(a, b, a === b) // 1 1 ture | a와 b가 바라보는 메모리 주소가 같기 때문에 true

a = 7 //새로운 메모리
console.log(a, b, a === b) // 7 1 false | a와b가 바라보는 메모리 주소가 다르기 때문에 false
let c = 1
// 처음에 a = 1 를 할당했던 메모리에 할당
console.log(b, c, b === b)// 1 1 true

// Reference Type
let a = {k:1}
let b = {k:1}
console.log(a, b, a === b) //{k:1} {k:1} false

a.k = 7
b = a //b 와 a는 같은 메모리 주소를 바라보게 됨
console.log(a,b,a === b) //{k:7} {k:7} ture

a.k = 2	// 같은 메모리 주소를 가지기 때문에 a의 k값이 바뀌면 b의 값도 변함
console.log(a, b, a === b) //{k:2} {k:2} ture

let c = b//c는 b와 메모리주소가 같고 b는 a와 메모리주소가 같기 때문에 c 와 b의 메모리주소는 같음
console.log(a,b,c, a === c) //{k:2} {k:2} ture

shallow copy, deep copy

  • 할당
const user = {
    name: 'hun',
    age: 50,
    emails: ['abc@gmail.com']
}

const copyUser = user  //할당만 하게 되면 같은 메모리 주소값을 가짐
console.log(copyUser === user) //true

user.age =22
console.log('user', user) //{name: 'hun', age: 22, emails: Array(1)}
console.log('copyuser', copyUser) //{name: 'hun', age: 22, emails: Array(1)}
//copyUser의 age도 수정됨 (같은 메모리 주소를 참조하기 때문)
//이것을 해결하기 위해 복사함
  • 얕은 복사
    리터럴 방식을 이용해서 해당 참조형 데이터를 새로 만들어 할당하거나, 전개 연산자를 이용함
const copyUser = Object.assign({}, user) //새로운 주소로 복사됨
//전개 연산자를 사용해서도 가능
//const copyUser = {...user}

console.log(copyUser === user) //false
user.age = 22
console.log('user', user) //{name: 'hun', age: 22, emails: Array(1)}
console.log('copyuser', copyUser) //{name: 'hun', age: 50, emails: Array(1)}
  • 깊은 복사
    assign를 이용하여 복사시 객체 내에 원시형 데이터는 다른 메모리 주소를 가지기 때문에 영향을 주지 않지만
    내부에 참조 데이터는 결국 같은 메모리 주소를 가지기 때문에 서로 영향을 미침. 따라서 깊은 복사를 이용해서 참조형 데이터도 복사를 해줘야함
user.emails.push('def@gmail.com')
console.log(user.emails === copyUser.emails) //ture
//얕은 복사시 emails는 참조형 데이터기 때문에 메모리 주소값이 같음
------------------------------------------------------------
const copyUser = _.cloneDeep(user) //lodash를 이용한 deep copy
console.log(user.emails === copyUser.emails) //false

0개의 댓글