programing

각 마지막 반복에 대한 캐치

oldcodes 2023. 8. 17. 21:52
반응형

각 마지막 반복에 대한 캐치

arr = [1,2,3];
arr.forEach(function(i){
// last iteration
});

루프가 끝날 때 어떻게 잡습니까?할수있어if(i == 3)내 배열 번호가 몇 번인지 모를 수도 있습니다.

ES6+대한 업데이트된 답변도 참조하십시오.


arr = [1, 2, 3]; 

arr.forEach(function(elem, idx, array){
   if (idx === array.length - 1){ 
       console.log("Last callback call at index " + idx + " with value " + elem ); 
   }
});

출력:

Last callback call at index 2 with value 3

이 작동 방식은 테스트입니다.arr.length배열의 현재 인덱스에 대해 콜백 함수로 전달됩니다.

2021 ES6+ 정답:

    const arr = [1, 2, 3];

    arr.forEach((val, key, arr) => {
      if (Object.is(arr.length - 1, key)) {
        // execute last item logic
        console.log(`Last callback call at index ${key} with value ${val}` ); 
      }
    });

나는 이런 방식을 선호합니다.

arr.forEach(function(i, idx, array){
   if (idx + 1 === array.length){ 
       console.log("Last callback call at index " + idx + " with value " + i ); 
   }
});

더 긍정적인 것 같습니다.

const arr= [1, 2, 3]
arr.forEach(function(element){
 if(arr[arr.length-1] === element){
  console.log("Last Element")
 }
})

언급URL : https://stackoverflow.com/questions/29738535/catch-foreach-last-iteration

반응형