Javascript 잘 몰랐던 함수들 익히기

박경현·2022년 7월 19일
1

splice,slice,reduce,filter,promise, async- await를
하나하나 찾아보면서 여기 이해한 내용을 적어보려고 한다.

splice

Array.prototype.splice() 배열의 기존 요소를 삭제 또는 교체하거나 추가함
원본배열이 바뀌고 리턴 값이 제거된 값이다!!
splice(시작인덱스, 몇개 삭제할지, 추가할것들)

var arr = [1,2,3,4,5,6,7]

var arr1 = arr.splice(3)
console.log(arr) // [1,2,3] 
console.log(arr1) // [4,5,6,7]

var arr2 = arr1.splice(2,0,'add')
console.log(arr1) // [4,5,'add',6,7]
console.log(arr2) // []

slice

Array.prototype.slice() begin부터 end전까지 복사본을 새로운 배열객체로 반환한다.
원본배열은 수정 X

var arr = [1,2,3,4,5]
var arr1 = arr[1:3] // [2,3]
var arr2 = arr[-3] // [3,4,5] 맨 뒤에가 -1 이기 때문에 -3 -2 -1 순으로 나온다!

reduce

배열의 각 요소를 다 돌며 콜백함수에 있는 실행 값을 누적해서 하나의 결과값을 반환 - 자신이 바뀌지는 않음!
배열.reduce((누산값 현재요소값 현재요소의 index 현재배열)=> {return 다음 누산값},초기누산값)

var arr = [1,2,3,4,5]
var totalValue = arr.reduce(function(accumulator, currentValue, index) {
	return accumulator + currentValue
})
//초기 누산값이 안정해져 있어서 초기 누산값은 0번째 index로 저장됨! 순회하면서 accumulator에 들어감!

var arr2 = [{value:1}, {value:2}, {value:3}]
var totalValue = arr.reduce(function(accumulator, currentValue, index) {
	return accumulator + currentValue.value
},0)
// 이러면 초기값이 0이고 객체로 되어있지만 초기누산값 설정덕분에 오류는 안걸린다!

Promise

비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과값을 나타냅니다.
.then을 따라 계속 이동함!

case 1:
// reject가 resolve보다 위에 있으면 'after resolve' 까지 나오고 에러 메세지 뜸! 
new Promise((resolve, reject) => {
  console.log('inside promise')
  reject(new Error('first reject'))
  console.log('before resolve')
  resolve('Firsit resolve')
  console.log('after resolve') //이거 나옴! 콜스택이 빌때까지 실행이니까!
})
  .then((value) => {
    console.log('inside firth then')
    console.log(value)
  })
  .catch((err) => {
    console.log(err)
  })

case2:
// 프로미스를 함수에 적어서 리턴 해주면 .then으로 체이닝 하기 쉽다!
function returnPromiseForTimeout() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(Math.random())
    }, 1000)
  })
}

returnPromiseForTimeout()
  .then((value) => {
    console.log(value)
    return returnPromiseForTimeout()
  })
  .then((value) => {
    console.log('then2', value)
    return returnPromiseForTimeout()
  })

returnPromiseForTimeout()

async- await

async는 프로미스를 돌려주는함수!
async함수는 다른 async함수 안에서 await할 수 있다

/**
 *
 * @param {number} duration
 */

async function sleep(duration) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(undefined)
    }, duration)
  })
}

async function main() {
  console.log('first')
  await sleep(1000)
  console.log('2')
  await sleep(1000)
  console.log('3')
  await sleep(1000)
  console.log('finish')
}

main()

async에서 오류는 try catch구문을 적어서 에러를 잡으면 된다

const fs = require('fs')

/* eslint-disable no-new */
/* eslint-disable no-console */

async function main() {
  try {
    const result = await fs.promises.readFile('.gitigenore', 'utf-8')
    console.log(result)
  } catch (err) {
    console.log(err)
  }
}
main()

Lexical Scope

  • Lexical scope
    함수 안에 블록에서 밖에 있는 변수에 접근이 가능한 것을 의미한다!
profile
SW로 문제를 해결하려는 열정만 있는 대학생

0개의 댓글