JS 특정 값 개수 구하기
자바스크립트에서 특정 값의 개수를 구하는 함수를 아래와 같이 작성하였다.
예를 들어 함수 counterCharacter('Abcea', 'a')는 'Abcea' 에서 a가 몇 번 들어갔는지 세는 함수로 대소문자 구분이 없다.
즉, 위 예시의 경우 실행값은 2가 나와야 한다.
fucntion counterCharacter(word, ch){
let count = 0;
for (let i = 0; i < word.length; i++>){
if (word[i].toUppercase() === ch.toUpperCase()) {
count ++;
}
}
return count;
}
console.log(countCharacter('AbaCedEA', 'E'));
4-(1). return count 을 for 문 안에 써준 경우
function countCharacter(AbaCedEA, E) {
let count = 0;
for (let i = 0; i < word.length; i++) {
if (word[i].toUpperCase() === ch.toUpperCase()) {
count++;
return count;
}
}
}
console.log(countCharacter("AbaCedEA", "E"));
4-(2). return count 을 for문 안에 써준 경우
function countCharacter(AbaCedEA, E) {
let count = 0;
for (let i = 0; i < word.length; i++) {
if (word[i].toUpperCase() === ch.toUpperCase()) {
count++;
}
return count;
}
}
console.log(countCharacter("AbaCedEA", "E"));
결과는 모두 0이 나오게 되는데 if 의 조건이 충족한 경우, count++로 내려온 후 바로 return 으로 해당 함수를 종료시키기 때문이다.