Slider Javascript 줄이기
원래 하던 방식
var index=0;
var item = Math.floor(Math.random()*5);
hero(item);
function hero(n){
ul=document.querySelectorAll('#header_hero_backgrounds>ul');
if(index==ul.length){
index=0;
}
if(n == undefined){
for(i=0; i<ul.length; i++){
var beNum=index-1;
if(beNum==-1){
beNum=4;
}
if(i==index){
ul.item(i).setAttribute('class', 'hero on');
} else if(i==beNum){
ul.item(beNum).setAttribute('class', 'hero out');
} else{
ul.item(i).setAttribute('class', 'hero');
}
}
//자동
} else {
//처음
ul.item(n).setAttribute('class', 'hero firston');
index = n;
console.log(index);
}
index++;
}
setInterval(hero, 3000);
기본 베이스
let index = 0;
function hero(){
let ul = document.querySelectorAll('#header_hero_backgrounds > ul');
if(index == ul.length) index = 0;
let beNum = (index == 0) ? (ul.length-1) : index -1;
ul.item(index).setAttribute('class','hero on');
ul.item(beNum).setAttribute('class','hero out');
index++;
setTimeout(hero,3000);
}
hero();
삼항 연산자를 사용했다.
let beNum = (index == 0) ? (ul.length-1) : index -1;
풀어쓰자면 이렇게 두가지 방식
1.
if(index == 0){
beNum = ul.length -1;
}else{
beNum = index -1;
}
2.
let beNum = index -1;
if(beNum == -1){
beNum = ul.length-1
}
4 possible ways to move slide.
1. forEach 문에 재귀함수이자 익명함수를 사용해서 NodeList 의 value값과 key 값을 가지고 왔다.
가장 기본적인 우리가 원래 하던 방식
ul.forEach((value,key)=>{
console.log(index,key,value);
if(key == index){
value.setAttribute('class','hero on');
}else if(beNum == index){
value.setAttribute('class','hero out');
}else{
value.setAttribute('class','hero');
}
});
2. ul은 nodelist라서 ul의 value값들을 객체 형태로 변환후 새로운 변수에 담아줬다.
index 와 beNum의 value를 삭제해준뒤 둘을 제외한 나머지 값에 class hero를 줬다.
newUl = Object.values(ul); // nodelist인 ul을 object(객체)형태로 바꿔서 새로운 변수에 담았다.
newUl[index] = undefined;
newUl[beNum] = undefined;
newUl.forEach(value =>{
if(value != undefined){
value.setAttribute('class','hero');
}
});
3. forEach 문을 사용해서 value값과 key값을 받아온다.
안에 if문을 이용해서 index나 beNum과 같지 않은 key값들의 class를 hero로 바꿔준다.
ul.forEach((value,key) => {
if(key != index && key != beNum){
value.setAttribute('class','hero');
}
})
4. filter
newUl = Object.values(ul).filter((value,key)=> {
if(key!=index && key!=beNum) value.setAttribute('class','hero');