Home > database >  Converting forEach to map
Converting forEach to map

Time:11-22

Some people said that forEach inside this function is not good and that i should use maps. So, im wodering how do i use maps for this

Some people said that forEach inside this function is not good and that i should use maps. So, im wodering how do i use maps for this: I also want this to be a reusable function so i could just call it anywhere

How do i make this code much cleaner. Without Jquery

JS:

const about = document.getElementById('about');
const numbers = document.querySelectorAll('.number');
const svgEl = document.querySelectorAll('svg circle');
const counters = Array(numbers.length);
const intervals = Array(counters.length);
counters.fill(0);

function moveprogressbar() { numbers.forEach((number, index) => {
    intervals[index] = setInterval(() => {
        if(counters[index] === parseInt(number.dataset.num)){
            clearInterval(counters[index]);
        } else{
            counters[index]  = 1;
            number.textContent = counters[index]   "%";
            svgEl[index].style.strokeDashoffset = Math.floor(472 - 440 * parseFloat(number.dataset.num / 100));
        }
    }, 20);
 });
}

CodePudding user response:

just change forEach with map keyword to use map and Unlike forEach map will return you a new array but if you just want to iterate i think forEach is good choice over map

const about = document.getElementById('about');
const numbers = document.querySelectorAll('.number');
const svgEl = document.querySelectorAll('svg circle');
const counters = Array(numbers.length); 
const intervals = Array(counters.length);
counters.fill(0);
let numberArray =[]
numberberArray.push[numbers]
function moveprogressbar() { numberArray.map((number, index) => {
intervals[index] = setInterval(() => {
    if(counters[index] === parseInt(number.dataset.num)){
        clearInterval(counters[index]);
    } else{
        counters[index]  = 1;
        number.textContent = counters[index]   "%";
        svgEl[index].style.strokeDashoffset = Math.floor(472 - 440  
* parseFloat(number.dataset.num / 100));
    }
   }, 20);
 });
}

CodePudding user response:

It's just simple use map keyword instead of forEach

function moveprogressbar() { numbers.map((number, index) => {
        intervals[index] = setInterval(() => {
        if(counters[index] === parseInt(number.dataset.num)){
         clearInterval(counters[index]);
         } else{
        counters[index]  = 1;
        number.textContent = counters[index]   "%";
       svgEl[index].style.strokeDashoffset = Math.floor(472 - 440 * parseFloat(number.dataset.num / 100));
               }
           }, 20);
        });
       }
  • Related