H
H
helpmeplease1962022-04-21 14:56:13
JavaScript
helpmeplease196, 2022-04-21 14:56:13

How to return the last true value in a for loop if there were more iterations after that?

The goal is to display 8 random numbers on the screen and find the number whose sum of digits is minimal (for example, 12>> 1+2=3)
Problem: if the condition is met and the variable K is assigned a value, then at the next iteration, if the condition is not met and K needs to keep its previous value, K=undefined .

I understand why this happens, but how to make it so that K would not be updated with each iteration, if the condition is not met, but store the previous value


let min=100
for(let i=1; i<=8; i++){

let a = Math.floor(Math.random()*(99-10)+10)
let k
let tens=Math.floor(a /10)
let unit=a%10
let sum = tens+unit
if (sum k=a
min=sum
}

alert (a + "/" + tens + "/"+ unit+ '/' +sum +"/"+ min+"/"+k)
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MrColdCoffee, 2022-04-21
@MrColdCoffee

var min=100
var k

for(let i=1; i<=8; i++){

let a = Math.floor(Math.random()*(99-10)+10)
let tens=Math.floor(a/10)
let unit=a%10
let sum = tens+unit

if (sum < min) {
k=a
min=sum
}

alert (a + "/" + tens + "/"+ unit+ '/' +sum +"/"+min+ "/"+k )
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question