There is a code, it only works when you specify static data in var = mass []. But my value is generated by random numbers and at the same time the array itself outputs a from min / max value - NaN

How to fix?

var mass = []; var min = mass[0]; var max = mass[0]; for (i = 0; i < 20; i++) { mass[i] = Math.round(Math.random() * 100); } for (j = 0; j < mass.length; j++) { max = Math.max(max, mass[j]); min = Math.min(min, mass[j]); if (max < mass[j]) { max = mass[j]; } } console.log(mass, min, max); 
  • What do you think are min , max on the first iteration? - MedvedevDev
  • the same NaN is only displayed as many times as there are values ​​in the array. - Bender
  • ooookey, I will simplify the task a little, what are they equal to before the execution of the cycles? Why are they equal to this? - MedvedevDev
  • Yes ... things! Do not torture already) - sepgg
  • equal to the first value of the cycle. In fact, we do not know what value min / max .. - Bender

1 answer 1

  var mass = []; for (i = 0; i < 20; i++) { mass[i] = Math.round(Math.random() * 100); } var min = mass[0]; var max = mass[0]; for (j = 0; j < mass.length; j++) { max = Math.max(max, mass[j]); min = Math.min(min, mass[j]); if (max < mass[j]) { max = mass[j]; } } console.log(mass, min, max); 
  • Setting variables so is a bad pattern. - MedvedevDev
  • @MedvedevDev corrected. Just the essence was different. - Daniyal Lukmanov