Codemaster123
Codemaster123

Reputation: 47

How can I make this to a loop?

How can I make this to a loop? the array tabProsent contains 70 numbers.

var startVerdi=1000;

 if(slider.value==tab[0]){
    output2.innerHTML = startVerdi*tabProsent[0];
  }

  if(slider.value==tab[1]){
    output2.innerHTML = startVerdi*tabProsent[0]*tabProsent[1];
  }

  if(slider.value==tab[2]){
    output2.innerHTML = startVerdi*tabProsent[0]*tabProsent[1]*tabProsent[2];
  }

  if(slider.value==tab[3]){
    output2.innerHTML = startVerdi*tabProsent[0]*tabProsent[1]*tabProsent[2]*tabProsent[3];
}

Upvotes: 0

Views: 64

Answers (4)

Anton
Anton

Reputation: 2703

Based on the comments under the question and answer from Patrick Roberts, here is working example:

// Prepare data:
var startVerdi = 1000;
let tabProsent = [];
for (let i = 0; i < 70; i++) tabProsent.push(Math.random() * 0.13 + 1);

function sliderChanged(val) {
  const index = val - 1950;
  const total = tabProsent.slice(0, index + 1).reduce(
    (acc, cur) => acc * cur, startVerdi
  );
  document.getElementById('result').innerHTML = total;
}
<input type="range" min="1950" max="2020" onchange="sliderChanged(this.value)" oninput="sliderChanged(this.value)" />

<label id="result">?</label>

Upvotes: -1

Patrick Roberts
Patrick Roberts

Reputation: 51826

You can use the array methods indexOf(), slice(), and reduce():

var startVerdi=1000;
var index = tab.indexOf(slider.value);

if (index !== -1) {
  output2.innerHTML = tabProsent.slice(0, index + 1).reduce(
    (acc, cur) => acc * cur, startVerdi
  );
}

Upvotes: 2

Nikola Vanevski
Nikola Vanevski

Reputation: 44

Here is a simple and understandable method : you need two loops:

  • One to find the index of tab that corresponds to the slider value
  • Another (inner loop) to create the product of values of tabProsent that are smaller or equal to the index of tab:

const MAX_TAB_IDX = 69; // 0 to 69 gives 70 values
let startVerdi=1000;

for(let idx=0; idx<=MAX_TAB_IDX; idx++) { // First loop

    if(slider.value == tab[idx]) { // We found it!! Lets calculate the product..

        let product=1;
        for(let subidx=0; subidx <= idx; subidx ++) // Second loop
            product *= tabProsent[subidx];

        output2.innerHTML = startVerdi * product;
        
        break; // This is to stop the loop!
    }
}

There are other more elegant ways (for example, using slice and map functions) - this is so you can understand how it works.

Upvotes: 0

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5766

You could do something like this -

var startVerdi=1000;

for(let i=0;i<70;i++){        // check for tab[0], tab[1] and so on...
  if(slider.value == tab[i]){
    let temp = startVerdi;
    for(let j=0;j<=i;j++){
      temp = temp * tabProsent[j]  // multiply with tabProsent[0], tabProsent[1] and so on...
    }
    output2.innerHTML = temp;
  }
}

Upvotes: 1

Related Questions