Home > OS >  Convert this long console.log to a loop
Convert this long console.log to a loop

Time:10-15

I have to convert temperature in javascript

So I made the first for loop to console all the fahrenheit temps, I then created a function to convert fToC. It all works and I get my results but is there a way to loop the long console log to convert fToC?

for (let fahrenheit = 20; fahrenheit <= 120; fahrenheit = fahrenheit   5) {
  console.log(fahrenheit);
}

function ftoC(fahrenheit) {
  let celcius = (fahrenheit - 32) / 1.8;
  return celcius;
}
console.log(ftoC(20));
console.log(ftoC(25));
console.log(ftoC(30));
console.log(ftoC(35));
console.log(ftoC(40));
console.log(ftoC(45));
console.log(ftoC(50));
console.log(ftoC(55));
console.log(ftoC(60));
console.log(ftoC(65));
console.log(ftoC(70));
console.log(ftoC(75));
console.log(ftoC(80));
console.log(ftoC(85));
console.log(ftoC(90));
console.log(ftoC(95));
console.log(ftoC(100));
console.log(ftoC(105));
console.log(ftoC(110));
console.log(ftoC(115));
console.log(ftoC(120));

CodePudding user response:

Since it's incrementing by a fixed number, there's a very simple loop you could use. Here's a for:

const min = 20;
const max = 120;
for(let i = min; i <= max; i =5)
{
    console.log(ftoC(i));
}

Or a while:

let i = 20;
const max = 120;
while(i <= max)
{
    console.log(ftoC(i));
    i  = 5;
}

CodePudding user response:

Shorter and more modern

const ftoC = fahrenheit => ((fahrenheit - 32) / 1.8).toFixed(2);
const res =  [];
[...Array(141).keys()] // create an array from 0-141
  .slice(20)           // chop the first 20 
  .forEach((_,i) => { if (i%5 === 0) res.push(`${i}C: ${ftoC(i)}F`) // save if i modulo 5 is 0
  });
  document.querySelector('pre').innerHTML = res.join('<br/>');
<pre></pre>

  • Related