js 기본 문법 강의를 듣고 간단한 미니게임을 구현해봤는데 키워드만 떠오르고 코드 짜기가 여전히 어려웠다...
특히 배열 부분 개념이 덜 잡힌 것 같아서 10가지 기초문제를 풀어보았다.
Array 연습문제(기본)
const fruits = ['apple', 'banana', 'orange'];
const str = fruits.join();
console.log(str);
// 결과값 = apple,banana,orange
join()
: 배열의 모든 요소를 쉼표나 지정된 구분 문자열로 구분하여 연결한 새 문자열을 만들어 반환한다.예시)
1. join()
: 아무것도 적지 않았을 경우
=> apple,banana,orange
2. join('')
: '' 을 적었을 경우
=> applebananaorange
3. join('-')
" '-' 을 적었을 경우
=> apple-banana-orange
const fruits = '🍎, 🥝, 🍌, 🍒';
const arr = fruits.split(',');
console.log(arr);
// 결과값 = (4) ['🍎', ' 🥝', ' 🍌', ' 🍒']
split()
: 지정한 구분자를 이용하여 여러 개의 문자열로 나눈다.const array = [1, 2, 3, 4, 5];
const result = array.reverse();
console.log(result);
console.log(array);
// 결과값 = (5) [5, 4, 3, 2, 1] [[Prototype]]: result(0)
// array 배열도 바뀜 (5) [5, 4, 3, 2, 1] [[Prototype]]: Array(0)
reverse()
: 배열의 순서를 반전const array = [1, 2, 3, 4, 5];
const newArr = array.slice(2, 5);
// 배열에서 원하는 부분만 return해서 받아옴, 마지막 숫자는 배제됨
console.log(newArr);
console.log(array);
// 결과값 = (3) [3, 4, 5]
// array = (5) [1, 2, 3, 4, 5]
slice(시작값, 마지막값)
: 첫번째 값부터 마지막 값까지 잘라내어 새로운 배열로 반환한다.Array 연습문제(기본+)
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),
];
위 코드를 사용하여 나머지 연습문제를 풀어보았다.
const result = students.find((student) => student.score === 90);
console.log(result);
// 결과값 = Student {name: 'C', age: 30, enrolled: true, score: 90}
find()
: 찾으려는 값을 콜백함수를 활용하여 배열에서 함수를 만족하는 첫 번째 요소를 반환한다.const result = students.filter((student) => student.enrolled === true);
console.log(result);
// 결과값 = (3) [Student, Student, Student]
// 0: Student {name: 'A', age: 29, enrolled: true, score: 45}
// 1: Student {name: 'C', age: 30, enrolled: true, score: 90}
// 2: Student {name: 'E', age: 18, enrolled: true, score: 88}
// length: 3
// [[Prototype]]: Array(0)
filter()
: 콜백함수의 filter를 통과한 요소만 반환하여 배열로 나타낸다.const result = students.map((student) => student.score)
console.log(result);
// 결과값 = (5) [45, 80, 90, 66, 88]
map()
: 기존 배열을 순회하면서 원하는 값만 가져와 새로운 배열을 복사한다.const result = students.some((student) => student.score < 50)
console.log(result);
// 결과값 = true
some()
: 배열 안의 어떤 요소라도 주어진 판별 함수를 적어도 하나라도 통과하는지 확인한다. 하나라도 통과한다면 >> true 값이 나온다.every()
: 배열 안의 함수를 '모두' 통과하는지 확인한다. 하나라도 맞지 않다면 >> false 값이 나온다.즉, some()
은 하나라도 만족하면 true // every()
는 모두 만족해야 true
const result = students.reduce((prev, curr) => prev + curr.score, 0)
console.log(result / 5);
// 결과값 = 73.8
reduce()
: 배열에 있는 모든 요소들의 값을 누적하거나 모아둘 때 사용한다.const result = students.reduce((prev, curr) => {
console.log(prev);
console.log(curr);
return prev + curr.score;
}, 0);
prev와 curr를 콘솔창으로 확인해보면 다음과 같다.
첫번째 요소의 score 값은 45인데, 다음 변수의 score 값이 80이므로 45와 더해져 125로 출력된다.
여기서 A 학생은 prev가 되고 B 학생의 값이 curr이 되어 reduce() 메소드에 의해 누적된다.
const result = students.map(student => student.score).join();
console.log(result)
// 결과값 = 45, 80, 90, 66, 88
const result = students.map(student => student.score).sort((a,b) => a - b).join();
console.log(result)
// 결과값 = 80,90,66,88
sort(a,b)
: 배열에 있는 요소들의 값을 정렬할 때 사용한다.비슷한 방법으로 이것저것 활용해보니까 조금은 감이 잡힌 것 같아서 재미있었다! 점점 수준 높여서 복잡한 것도 후루룩 풀 수 있도록 연습해야지!
출처