반응형

var / let

var은 

var a = 'a'

var a= 'b'

가 가능하므로 let을 사용

let은 한번 선언하면 재선언불가하고 재할당 가능하다.

 

== / ===

==은 자동으로 타입변환을 하여 값을 비교하지만

===은 타입변환을 하지않고 값을 비교한다. 따라서 값과 타입이 같아야한다.

 

for in / for of

for in은 객체에 사용(객체 프로퍼티 접근) => ex) foo = { name : 'foo' ~~~~}

for of는  iterable한(반복되는) 객체에 사용, 주로 값을 찾을 때 사용(원소에 접근) => foo = [1, 2, 3 ~~]

 

함수 표현식

함수 리터럴로 하나의 함수를 만들고 생성된 함수를 변수에 할당함

//함수 이름 사용
fuction add(x,y){
	return x+y
}
add(3,4)



//익명함수 사용 => 위와같이 함수 이름이 없다
const add = function(x,y){
	return x+y
}

add(3, 4)

 

기본인자

const print = fucntion ( defaultVal = 'default'){
	console.log(defaultVal)
}

 

함수 호이스팅

//호이스팅

add(3, 4) //=>undefined
function add (x, y){
	return x+y
}

add(3, 4) // 에러
const add = function (x, y){
	return x+y
}

console.log(add)//undefined => add 선언 전 undefined로 초기화
add(3, 4)// 에러 add는 함수가 아님
var add = function (x, y){
	return x+y
}

함수를 const 변수에 할당하여 변수처럼 취급

 

Arrow function => 함수 간단히

const nothing = function (x){
	return x
}

console.log(nothing(1))

//fucntion 삭제 가능
const nothing1 = (x) =>{
	return x
}
console.log(nothing1(1))

//괄호 삭제가능 매개변수가 한개일 경우
const nothing2 = x =>{
	return x
}
console.log(nothing2(1))

//중괄호, return 삭제가능 함수 안 표현식이 1개인 경우만
const nothing3 = x => x
console.log(nothing3(1))

 

 

배열관련 메소드

reverse => 배열 원소 반대로 정렬

push => 맨끝에 원소 추가

pop => 맨끝 원소 삭제

unshift => 맨 앞에 원소 추가

shift => 맨 앞 원소 삭제

include(val) => 배열이 val을 가지고 있는지 판단 (참/거짓)

indexOf(val) => val이 존재하면 첫번째로 찾은 val의 인덱스값 반환, 없으면 -1 반환

const num = [1, 1, 3, 1, 3]

num.indexOf(3) => 2반환

join(구분자) => 기본(join())은 "," 

const test = [1, 2, 3]

console.log(test.join("+"))
console.log(test.join("-"))
console.log(test.join(","))
console.log(test.join(" and "))

 

*callback 함수

익명함수의 대표적인 예시

함수를 등록하기만 하고 이벤트가 발생하거나 특정 시점에 도달했을 때 시스템에서 호출되는 함수

or

함수의 인자로 넘겨서 코드 내부에서 호출되는 함수

 

 

forEach

const arr = [1, 2, 3, 4, 5]

arr.forEach((element, index, array) => {
    console.log('elemnet :'+ element)
    console.log('index :'+index)
    console.log(array)
})

===========================================
elemnet :1
index :0
[ 1, 2, 3, 4, 5 ]
=>[ 1, 2, 3, 4, 5 ]배열에서 원소 1의 index는 0

elemnet :2
index :1
[ 1, 2, 3, 4, 5 ]
=>[ 1, 2, 3, 4, 5 ]배열에서 원소 2의 index는 1

elemnet :3
index :2
[ 1, 2, 3, 4, 5 ]
=>[ 1, 2, 3, 4, 5 ]배열에서 원소 3의 index는 2

elemnet :4
index :3
[ 1, 2, 3, 4, 5 ]
=>[ 1, 2, 3, 4, 5 ]배열에서 원소 4의 index는 3

elemnet :5
index :4
[ 1, 2, 3, 4, 5 ]
=>[ 1, 2, 3, 4, 5 ]배열에서 원소 5의 index는 4

 

 

map => 기존 배열을 새 배열로 만들 때 사용(기존 배열이 변하지 않음)

array.map(callbackFunction(element, index, array), thisArg)

thisArg = callback함수 내에서 this로 사용될 값

const arr = [1, 2, 3, 4, 5]

const returnArr = arr.map((element, index, array) => {
		console.log(element)
        console.log(index)
        console.log(array)
        return element*2;
    })
    
 console.log(returnArr)
 
 =========================
1
0
[ 1, 2, 3, 4, 5 ]

2
1
[ 1, 2, 3, 4, 5 ]

3
2
[ 1, 2, 3, 4, 5 ]

4
3
[ 1, 2, 3, 4, 5 ]

5
4
[ 1, 2, 3, 4, 5 ]


[ 2, 4, 6, 8, 10 ]

 

 

filter

콜백 함수의 반환값이 참인 값만 반환 => 필터링

const num = [10, 20, 30, 40, 50]

const result = num.filter((num)=>{
	return num>=30
})

console.log(result)

=> [30, 40, 50]

=>결과가 true를 반환한 원소들로만 배열을 만든다.

find는 요소를 반환

 

reduce => 콜백 함수의 반환값 acc에 누적

reduce(function(acc, currentValue, currentIndex, array){ , initialValue);

acc = 콜백의 반환값 누적

currentValue = 현재 처리할 요소 (옵션)

currentIndex = 현재 처리할 요소 인덱스 (옵션)

array = reduce() 호출할 배열 (옵션)

initialValue = 초기값 (옵션 => 초기값이 없으면 배열의 첫번째 요소 사용)

//콜백 함수 이용시 밑의 function처럼 콜백함수 이름을 적어도 되고 안적어도됨
const result = [0, 1, 2, 3, 4].reduce(function(acc, currentValue, currentIndex, array){
    console.log(`currentIndex : ${currentIndex}`);
    console.log(`currentValue : ${currentValue}`);
    console.log(`currentIndex : ${currentIndex}`);
    console.log(`acc : ${acc}`);
    return acc + currentValue;
}, 0); //acc의 초기값은 0

console.log("result:", result);

==========================
currentIndex : 0
currentValue : 0
currentIndex : 0
acc : 0

currentIndex : 1
currentValue : 1
currentIndex : 1
acc : 0

currentIndex : 2
currentValue : 2
currentIndex : 2
acc : 1

currentIndex : 3
currentValue : 3
currentIndex : 3
acc : 3

currentIndex : 4
currentValue : 4
currentIndex : 4
acc : 6

result: 10

 

find => callback 함수에 정의한 조건에 맞는 배열의 첫번째 요소를 리턴 (없으면 undefined)

find(callback(element, index, array)

const arr = [
  {name: 'a', age : 10}, 
  {name: 'b', age : 20},
  {name: 'c', age: 30}
];

const result = arr.find((arr) => {
	return arr.name == 'a'
})

console.log(result)

=>{ name: 'a', age: 10 }

 

 

some => callback함수에서 true를 리턴하면 true 리턴, 하나라도 참이면 참 반환

array.some(callback(currentValue, index, array), thisArg)

const num = [10,20,25,40,50]

const overThrity = num.some((val) => {
	return val>30
 })
 console.log(overThrity)
 
 
 const underThrity = num.some((val) => {
	return val<30
 })
  console.log(underThrity)
  
   const overFifty = num.some((val) => {
	return val>50
 })
   console.log(overFifty)
   
   
===========
true
true
false

 

 

every => callback함수에서 모든 요소가 참이면 참

const num = [10,20,25,40,50]

const overThrity = num.every((val) => {
	return val>30
 })
 console.log(overThrity)
 
 
 const underThrity = num.every((val) => {
	return val<30
 })
  console.log(underThrity)
  
   const underFifty = num.every((val) => {
	return val<=50
 })
   console.log(underFifty)
   
 ========
false
false
true

 

728x90
반응형
블로그 이미지

아상관없어

,