Javascript 헷갈렸던 내용, 새로 알게된 내용 정리
→ Array

Array API에 대하여

배열 중 특정 조건에 해당되는 요소 찾기 - find, filter

const studenets = [
  new Student('A' 29, true, 45),
  new Student('B' 28, false, 80),
  new Student('C' 30, true, 90),
  new Student('D' 40, false, 66),
  new Student('E' 18, true, 88),
]

const result = students.find(function(student, index){
  return student.score === 90;
});

// arrow function을 사용한 방식
const result = students.find((student) => student.score === 90);

find는 조건에 해당되는 첫번째 요소가 검색되면 find 함수 종료

조건에 해당되는 ‘모든’요소를 반환받고 싶을때는 filter 함수 사용

배열 안의 모든 요소를 가공해서 반환받고 싶을 때 - map 함수

const result = students.map((studen) => student.score);

특정 조건에 만족하는 요소가 있는지 없는지 여부 확인 - some

const result = students.some((studen) => student.score < 50);
//하나라도 조건에 만족하는 요소가 있으면 true

모든 요소가 특정 조건에 만족하는지 여부 확인 - every

const result = students.every((studen) => student.score <= 50);
//모든 요소가 조건에 만족하면 true

배열안에 있는 요소의 평균값을 구하려고 할 때 - reduce

이 경우에는 배열안의 모든 값을 호출해서 ‘누적’해야하는 일이 필요

const result = students.reduce((pre, curr) => {
  console.log('---');
  console.log(pre);
  console.log(curr);
});
// 결과
---
45
80
---
undefined
90
---
undefined
66
---
undefined
88

누적이 되어야하는데 위처럼 undefined가 출력되면서 다음 요소로 넘어가는 문제가 발생한다.

바로 이러한 부분에서 return 이 필요하고, return에 명시한 값이 그 다음 반복프로세스 pre값에 할당되는 흐름. 따라서 아래와 같이 시작값을 0으로 정의하면서 return 정의 필요.

const result = students.reduce((pre, curr) => {
  console.log('---');
  console.log(pre);
  console.log(curr);
  return pre + curr.score;
}, 0);
// 결과
---
0
45
---
45
80
---
125
90
---
215
66
---
...

이 arrow function을 좀 더 축약해보면 아래처럼 작성 가능

const result = students.reduce((pre, curr) => prev + curr.score, 0);

따라서 평균 값은 
console.log(result / students.length);


정렬기능 - sort

const result = students.map((student) => student.score)
	.sort((a, b) => a - b) // 오름차순

	.sort((a, b) => b - a) // 내림차순


JSON

const rabbit = {
	name: 'tori',
  color: 'white',
  size: null,
  birthDate: new Date(),
  jump:()=>{
    console.log(`${name} can jump!`);
  }
}


let json = JSON.stringify(rabbit);
console.log(json);
// 결과
{"name":"tori", "color":"white", "size":null, "birthday":"2020-05-29T13L29:51.267Z"}
/* null은 그대로 null로 된다는 점, 함수는 json으로 변환 안되는 점(이 외에도 Symbol 등) */



json = JSON.stringify(rabbit, ['name','color','size']);
console.log(json);
// 결과
{"name":"tori", "color":"white", "size":null}
/* json에 특정 프로퍼티만 json으로 변환하는 방법 */



json = JSON.stringify(rabbit, function(key, value){
    console.log(`key : ${key}, value: ${value}`);
    return key == 'name' ? 'test' : value
});
console.log(json);
// 결과
key : , value: [object Object]
key : name, value: tori
key : color, value: white
key : size, value: null
key : birthDate, value: 2022-09-05T14:07:39.701Z
key : jump, value: ()=>{
    console.log(`${name} can jump!`);
  }
{"name":"test","color":"white","size":null,"birthDate":"2022-09-05T14:07:39.701Z"}

자바스크립트 오브젝트를 JSON으로 만드는 방법 : stringify

JSON을 자바스크립트 오브젝트로 만드는 방법 : parse

stringify를 serialize한다고하며 우리말로 ‘직렬화’라고 표현하기도 한다.

여기서 ‘직렬화’에 대한 내 생각은, 다른 곳에서 사용하기 위한 ‘변환’과 필요한 데이터 ‘정제’ 및 ‘나열’이라고 생각한다. ‘직렬’이라는 것의 의미가 ‘나열’한다는 맥락과 비슷하다는 점을 생각하면 더 쉽게 이해되기도 한다.

Leave a comment