[JS] 배열(Array)과 메서드

김태희·2023년 6월 10일
0

[HTML+CSS+JS] 시리즈

목록 보기
10/16
post-thumbnail

학습자료 : 드림코딩 자바스크립트 기초 강의(ES5+) - YOUTUBE

배열(Array)

  • 동일한 타입을 배열에 넣는것이 중요하다 !
  • JS에서는 타입이 다른 요소들을 배열에 넣을 수 있지만, 동일한 타입만 배열에 넣는것이 좋다 !

1. Declaration
배열의 선언방법

const arr1 = new Array(); //방법 1
const arr2 = [1, 2]; //방법 2

2. Index position
요소의 위치

const fruits = ['apple', 'banana'];
console.log(fruits);
console.log(fruits.length); //2
console.log(fruits[0]); //apple
console.log(fruits[3]); //undefined
console.log(fruits.length - 1); //last index

3. Looping over an array
반복문으로 배열의 모든 요소들을 출력하는 여러가지 방법

for(let i = 0; i<fruits.length; i++){
    console.log(fruits[i]);
}
for(let fruit of fruits){
  console.log(fruit);
}
fruits.forEach(function(fruit) {
  console.log(fruit)
});
fruits.forEach((fruit) => console.log(fruit));

4. Addition, deletion, copy

const fruits = ['apple', 'banana', 'peach'];

push : add an item to the end

fruits.push('strawberries', 'orange');
console.log(fruits);

pop : remove an item from the end

fruits.pop();
console.log(fruits);

unshift : add an item to the beginning

fruits.unshift('strawberries', 'orange');
console.log(fruits);

shift : remove an item to the beginning

fruits.shift();
fruits.shift();
console.log(fruits);

note ! shift, unshift are slower than pop, push

shift, unshift는 더 많은 동작이 필요해 pop과 push보다 실행속도가 느리다 !

splice : remove an item by index position

fruits.push('strawberries','peaches', 'lemon');
console.log(fruits);
fruits.splice(1, 1);
console.log(fruits);
fruits.splice(1, 1, 'pear');
console.log(fruits);
const fruits2 = ['coconut', 'kiwi'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);

5. Searching
find the index
요소 찾기 !

console.log(fruits);
console.log(fruits.indexOf('apple')); //배열에서의 위치 - 0
console.log(fruits.includes('apple')); //배열에 속하는지의 여부 - true
console.log(fruits.lastindexOf('apple')); //중복 시에 가장 뒤에 있는 요소의 위치

Array APIs

1. join()
make a string out of an array

배열로 문자열을 만들기

const fruits = ['apple', 'banana'];
let fruits_String
for(let fruit of fruits){
  fruits_String += ", "+fruit;
}
console.log(fruits_String); //My way
const result = fruits.join(', '); //use join()

2. split()
make an array out of a string

문자열로 배열 만들기

const fruits ='apple, banana'; 
const result = fruits.split(',');
console.log(result);

3. reverse()
make this array opposite

const array = [1, 2, 3, 4, 5];
array.reverse(); 

4. slice()
make new array without the first two elements

const array = [1, 2, 3, 4, 5];
const result = array.slice(0, 2);
console.log(result); //[1, 2]
console.log(array); //[1, 2, 3, 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. find()
find a student with the score 90

for(let i=0; i<students.length; i++){
  if(students[i].score != 90) continue;
  console.log(students[i].name+' 학생이 90점을 맞았습니다');
} //my way
const result = students.find((student) => student.score === 90);
console.log(result); //use find()

6. filter()
make an array of enrolled students

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

7. map()
make an array containing only the students' scores

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

8. some(), every()
check if there is a student with the score lower than 50

const result = students.some((student) => student.score < 50);
console.log(result);
const result2 = students.every((student) => student.score < 50);
console.log(result2);

9. reduce()
compute students' average score

const result = students.reduce((sum, add) => sum+add.score, 0);
console.log(result/students.length);

10. map() + join()
make a string containing all the scores

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

11. sort() - 정렬
sort in ascending order

const result = students.map(student =>student.score)
  .sort((a,b)=> a - b)
  .join();
console.log(result);


이로써 JavaScript의 기초를 어느정도 다진 것 같다, 내일부턴 알고리즘 문제를 풀것이다 !




0개의 댓글