솧디의 개발로그

[자바스크립트] 자주쓰는 배열 함수들 01 본문

Javascript 자바스크립트

[자바스크립트] 자주쓰는 배열 함수들 01

솧디_code 2022. 9. 26. 01:30

 

1.  join() 값 사이에 글 넣기 

const fruits = ['apple', 'banana', 'orange'];
  const result = fruits.join(' and ');//값 사이에 글넣기
  console.log(result);

 

2. split() 지정한 단위로 나누기 

const fruits = '🍎, 🥝, 🍌, 🍒';
  const result = fruits.split(',')//''의 단위로 나눠줌
  console.log(result)

 

3. reverse() 역순으로 값 배치 

const array = [1, 2, 3, 4, 5];
  const result = array.reverse(',')//역순으로 값 배치
  console.log(result)

 

4. slice(0,-1)배열에서 원하는 부분 가져오기

  const array = [1, 2, 3, 4, 5];
  const result = array.slice(2,5)//배열에서 원하는 부분만 가져오기
  console.log(array)
  console.log(result)

(괄호)안에는 배열의 자리를 지정해주면 되는데, (2,5)를 찍어보면 3,4,5가 출력된다.

배열은 0번부터 순서가시작하는데 앞은 배열 순서대로 찍어주면 되지만

마지막값을 가져오려면 -1을 해야한다, 즉 배열에 4번값을 불러오려면 4가아닌 5로 입력해야한다.

 


✅연습시 예제로 쓰면 좋아요 🔰출처: 드림코딩유튜브

class Student {
  constructor(name, age, enrolled, score) {
    this.name = name;
    this.age = age;
    this.enrolled = enrolled;
    this.score = score;
  }
}
const students = [
  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),
];

 🔉  5~10번은 위 의 코드로 사용한 배열함수 예시입니다. 

 

5. map() 항목의 값 불러오기

{
  const result = students.map((student)=>student.score);
  console.log(result)
  
}

map()은 배열안의 값들은 불러와 맵핑하는 것이다. 배열안에 들어있는 정보를 각각 불러와 원하는 조건으로 맞춰 끄집어와 

보여주는 것이라보면된다. 그래서 조건을 주어 맵핑하면 조건을 반영해 값이 달라진다.

 

{
  const result = students.map((student)=>student.score *2);
  console.log(result)
  
}

*2를 하면 출력값이 곱하기 2가 되어진다. 

 

[ 45, 80, 90, 66, 88 ]
[ 90, 160, 180, 132, 176 ]

 

 

6.  filter() 지정한 조건에 맞는 값만 불러오기

{
  const result = students.filter((student)=>student.enrolled);
  console.log(result)
}

 

7.  join() 데이터타입요소들 스트링으로 바꾸기 

const result= students
  .map((student)=>student.score)
  .join()//스트링으로 바꿔줌
  console.log(result);

 

 

8. sort()오름차순, 내림차순 으로 불러오기

{
  const result = students.map((student)=>student.score)//array항목불러오기
  .sort((a,b)=> b-a)//오름차순
  //.sort((a,b)=> a-b)//내림차순
  console.log(result)
}

 

9.  some(), every() 조건에 충족되는지 확인하기 

{
  
  const result = students.some((student)=>student.score<50);//지정한 조건이 하나라도 충족되면 true 
  console.log(result)

  const result2 = students.every((student)=>student.score >= 50);//지정한 조건이 모두다 충족되면 true 
  console.log(result2)

}

boolern값으로 확인함 true/false

 

 

10.  reduce() 모두 더하기(평균값구하기)

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


  console.log(result/students.length);
  
}

reduce()를 활용해 모든 배열에 지정된 값을 모두 더해주는 배열함수이다.

다만 reduce()는 조건에 prev,curr가 들어간다. 

prev: 이전값

curr: 현재값

prev가 0부터 시작해서 curr로 받은 스코어를 prev로 넣는 것이다.

그럼 prev가 0부터 스코어에 점수들을 더해 스코어에 할당된 값들을 계속 더해가게된다.

그래서 reduce()를 통해 스코어 합계가 완성된다.

 

 평균값은 console에 찍을 때 학생수length를 가져와 /나누어 주면된다.

Comments