고전 for문
const answer= [3, 1, 4, 6]
let strike = 0;
let ball = 0;
for (let i = 0; i < answer.length; i++) {
const index = value.indexOf(answer[i]);
if (index > -1) {
//일치하는 숫자 발견
if (index === i) {
//자릿수도 같음
strike += 1;
} else {
//숫자만 같음
ball += 1;
}
}
}
forEach문
const answer = [3, 1, 4, 6]
let strike = 0;
let ball = 0;
answer.forEach((element, idx) => {
const index = value.indexOf(element);
if (index > -1) {
//일치하는 숫자 발견
if (index === i) {
//자릿수도 같음
strike += 1;
} else {
//숫자만 같음
ball += 1;
}
}
});
▶ element는 배열의 요소
▶ idx는 answer의 index를 의미한다.
▶ index는 value의 index를 의미한다.
map()
const array = [1, 2, 3, 4]
const result = [];
for(let i =0; i<4; i++){
result.push(array[i]*2);
}
array.map((elemnet, i) => {
return element *2;
})
▶ map함수를 사용하는 경우 array 즉 원본 배열을 바뀌지 않으며
▶ array.map()을 통해서 array와 다른 "별도의 배열"이 만들어 진다.
fill()
Array(9)
[empty x 9]
Array(9).fill() //fill()함수에 매개변수를 넣지 않는 경우
[undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined ]
Array(9).fill(0)
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
Array(9).fill(0).map((element, idx) => {
return idx +1
})
[1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Array(45).fill().map((element, idx) => {
return idx + 1;
})
[1, 2, 3, 4, 5, .... 44, 45 ]
'렛츠기릿 자바스크립트' 카테고리의 다른 글
로또 만들기 self (공에 색깔 넣기) (0) | 2023.01.15 |
---|---|
로또 만들기 - splice( )★★+태그요소만들기+className추가 +sort() (0) | 2023.01.15 |
숫자야구게임 -self(3아웃인 경우) (0) | 2023.01.14 |
렛츠기릿 자바스크립트 8 - 숫자야구게임(for문, indexOf()) (0) | 2023.01.14 |
렛츠기릿 자바스크립트 7 (계산기) -self(연달아 계산) (0) | 2023.01.09 |