13.array.prototype.forEach()
array.prototype.forEach() 메서드는 주어진 함수 조건을 배열 요소 각각에 대해 실행하고, 그 결과를 반환합니다.
// 각 문제에 대한 정답과 해설을 표시
quizInfo.forEach((question, number) => {
const cbtQuestion = document.querySelector(`.cbt:nth-child(${number + 1})`);
const cbtAnswer = cbtQuestion.querySelector(".cbt__answer");
const cbtDesc = cbtQuestion.querySelector(".cbt__desc");
cbtAnswer.classList.remove("none");
cbtDesc.classList.remove("none");
cbtQuestion.classList.add(`bad`);
});
forEach 메서드는 반복 작업을 간단하게 처리하는 데 사용됩니다. 다른 반복 메서드에 비해 다소 제한적이지만, 배열의 각 요소에 대해 일부 작업을 수행해야 하는 간단한 상황에서 유용합니다.
각 문제에 대한 정답과 해설을 표시하고 해당 문제를 'bad' 클래스로 표시하는 부분입니다.
결과 확인하기
15.array.prototype.every()
array.prototype.every() 메서드는 주어진 함수를 모두 통과하는지 확인하고, 불린(true, false)로 반환합니다.
// 배열 선언
const names = ['Alice', 'Bob', 'Charlie', 'David'];
// 모든 요소가 3글자 이상인지 확인
const isThreeOrMore = names.every((name) => name.length >= 3);
console.log(isThreeOrMore); // 출력: true (모든 이름이 3글자 이상)
ames 배열의 모든 요소가 3글자 이상인지 확인하고 있으며, 모든 이름이 3글자 이상이므로 every() 메서드는 true를 반환합니다.
결과 확인하기
16.array.prototype.map()
array.prototype.map() 메서드는 주어진 함수를 호출하고, 그 결과를 모아서 만든 새로운 배열을 반환합니다.
const newArray = array.map((currentValue, index, array) => {
// currentValue: 현재 요소의 값
// index: 현재 요소의 인덱스
// array: 원래 배열 자체
// 변환 작업을 수행하고 새로운 요소 반환
return transformedValue;
map 메서드는 각 배열 요소에 대해 주어진 콜백 함수를 호출하고, 해당 요소를 변환한 후 새로운 배열에 그 변환된 요소를 넣습니다. 이는 기존 배열을 변경하지 않고 새로운 배열을 생성합니다.
결과 확인하기
21.array.prototype.join()
join() 메서드는 배열의 요소를 추가하여, 하나의 문자열로 반환합니다.
{
const fruits = ['apple', 'banana', 'cherry'];
// 구분자 없이 join() 메서드 사용
const joineStr = fruits.join();
console.log(joineStr);
// 출력: "apple,banana,cherry"
// 구분자 ',' 를 사용하여 join() 메서드 사용
const joineComma = fruits.join(',');
console.log(joineComma);
// 출력: "apple,banana,cherry"
// 구분자 ' - ' 를 사용하여 join() 메서드 사용
const joineHyphen = fruits.join(' - ');
console.log(joineHyphen);
// 출력: "apple - banana - cherry"
}
Array.prototype.join() 메서드는 배열의 모든 요소를 문자열로 결합하여 반환합니다.
구분자를 지정하지 않으면 기본적으로 쉼표로 구분되며, 구분자를 지정하면 해당 구분자로 요소가 구분됩니다.
결과 확인하기
"apple,banana,cherry"
"apple - banana - cherry"
22.array.prototype.pop()
pop() 메서드는 배열 마지막 요소를 제거하고, 제거한 요소를 반환합니다.주로 배열에서 마지막 요소를 제거하고 해당 요소를 얻고 싶을 때 사용됩니다.
{
const colors = ['red', 'green', 'blue'];
const removeColor = colors.pop();
console.log(removeColor); // 출력: "blue"
console.log(colors); // 출력: ["red", "green"]
}
pop() 메서드를 사용하여 배열 colors에서 마지막 요소 "blue"가 제거되고 해당 요소가 removedColor 변수에 반환됩니다. 배열의 길이가 하나 감소"blue"가 배열에서 사라진 것을 확인할 수 있습니다
결과 확인하기
"red", "green"
23.array.prototype.push()
push() 메서드는 배열 끝에 요소를 추가하고, 배열의 새로운 길이값을 반환합니다. 배열에 새로운 요소를 추가할 때 사용됩니다.
{
const colors = ['red', 'green'];
const newColors = colors.push('blue', 'yellow');
console.log(newColors); // 출력: 4 (새로운 배열의 길이)
console.log(colors); // 출력: ["red", "green", "blue", "yellow"]
}
push() 메서드를 사용하여 배열 colors에 "blue"와 "yellow" 요소가 추가되고, 배열의 길이는 2에서 4로 증가합니다. push() 메서드는 새로운 배길이인 4를 반환합니다.
결과 확인하기
"red", "green", "blue", "yellow