«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
Recent Posts
Recent Comments
관리 메뉴

뉴히의 개발 로그

[TIL] 20230531 - forEach안에 if로 alert을 띄우면 안되는 이유!/split(), join() 메서드 / 검색 띄어쓰기 삭제 본문

개발일지/TIL

[TIL] 20230531 - forEach안에 if로 alert을 띄우면 안되는 이유!/split(), join() 메서드 / 검색 띄어쓰기 삭제

뉴히 2023. 5. 31. 23:13

 alert창 한번만 띄우기 !!! 

어제 if 문으로 해결 된지 알았으나 아니었던것!

그 이유는! movies.forEach 안의 if문이라서 movies를 다 돌때 까지 alert창이  뜨는것 이였다 ㅎㅎㅎㅎ

console창을 보면 알 수 있다!

console을 잘 찍어봐야 하는 이유! 

let searchBtn = document.getElementById("search-btn");
searchBtn.addEventListener("click", function(){
let temp_html = '';  
// input 입력값
let inputValue =  document.getElementById("search-input").value.toLowerCase();
console.log('입력값->',inputValue);

movies.forEach((a)=>{
    let title = a['original_title'];
    let overview = a['overview'];
    let poster = a['poster_path'];
    let vote_avg = a['vote_average'];
    let _id = a['id'];

    // 대소문자, 띄어쓰기 관계없이 검색 가능
    inputValue = inputValue.split(' ').join('');
    let titleLower = title.split(' ').join('').toLowerCase();
    if(titleLower.includes(inputValue)){
        temp_html +=`<div class="card-list" id="${_id}">
                        <img src="https://image.tmdb.org/t/p/original${poster}" class="card-img" />
                        <div class="card-info">
                            <h5 class="card-title">${title}</h5>
                            <p class="card-text">${overview}</p>
                            <p class="card-avg">${vote_avg}</p>
                        </div>
                    </div>`       
        cardWrap.innerHTML = temp_html;
        console.log("영화잇음");
    } 
});

// 검색한 영화가 없을때
if(document.querySelectorAll(".card-list").length === 20 ){
    alert("검색된 영화가 없습니다! 다시 검색해 주세요.");
    window.location.reload();
}

forEach 밖으로 없으면 alert창을 띄워라로 바꾸니 진짜로 진짜진짜 해결!!!!

 

 검색 시 띄어쓰기 

let inputValue =  document.getElementById("search-input").value.toLowerCase(); //입력값
inputValue = inputValue.split(' ').join('');
let titleLower = title.split(' ').join('').toLowerCase(); // data의 제목들

이렇게 split 으로 스페이스를 기준으로 단어당 쪼개고 .join으로 합치면 띄어쓰기 없이 검색 가능하다 ㅎㅎ

 

 .split() 

String.prototype.split()

const str = 'The quick brown fox jumps over the lazy dog.';

const words = str.split(' ');
console.log(words[3]);
// Expected output: "fox"

const chars = str.split('');
console.log(chars[8]);
// Expected output: "k"

const strCopy = str.split();
console.log(strCopy);
// Expected output: Array ["The quick brown fox jumps over the lazy dog."]

 .join() 

Array.prototype.join()

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// Expected output: "Fire,Air,Water"

console.log(elements.join(''));
// Expected output: "FireAirWater"

console.log(elements.join('-'));
// Expected output: "Fire-Air-Water"