As the title stated, I am trying to do a javascript in which the user enters a digit between 0-9. It will then summarize all of the numbers who's lattermost digit contains the user's digit, i.e. if the user selects 7 it summarizes 7, 17, 27, 37, 47, 57, 67, 77, 87, and 97. However, it just returns a 0. Please help.
<html>
<head>
</head>
<body>
<input type="text" id="write">
<button id="knapp">Klicka på mig!</button>
<div id="box"></div>
<script>
document.getElementById("knapp").addEventListener("click", funktion);
var summa = 0;
var summa2 = 0;
function funktion(){
let imported = document.getElementById("write").value;
for(let i = 0; i < 100; i ){
summa = i;
if((i '').indexOf(imported)){
i = summa2;
document.getElementById("box").innerHTML = summa2;
}
}
}
</script>
</body>
</html>
CodePudding user response:
This can generally be summarized as:
const found = [];
let searchFor = '7';
for(let i = 0; i < 100; i ){
if((i '').endsWith(searchFor)){
found.push(i);
}
}
console.log(found);
I think endsWith
is much easier to reason about than indexOf
, which returns -1
when not found, by the way.
Storing what's found in an array is also easier, and you can later get a delimited string back if you need.
Edit
Going back to the original one, maintaining variables inside and outside of a function generally isn't a good idea, and really isn't necessary, either, so I've removed summa
and summa2
.
Inside of the loop, you were setting one of these global variables to the current index, for a reason I don't know, so that was removed.
As noted, indexOf
returns the position in a string that a substring was found. When you, for instance, test '9'.indexOf('7')
you'll get -1
, which is not found, however when tested for truthiness in JavaScript, will get converted to true. So pretty much everything except what you are looking for is true. You could use !
to then negate that, but that's just getting uglier.
After your test, you are adding summa2
on to i
, however summa2
is never changed from the initial value of 0
.
Lastly, inside of your loop, you are constantly settings the value of a text box, 100 times, to the value of summa2
, which as previously noted, is always 0
.
Edit 2
This code does not sum up numbers, it just gets the numbers and it is assumed that summing them should be pretty easy. It is unclear from the OP's sample data versus the words they use what exactly they are going for.
CodePudding user response:
remove summa = i;
and change i = summa2;
to summa2 = i;
.
Place document.getElementById("box").innerHTML = summa2;
after for
block. I didn't try, but should work.
I would do totally different way:
if you need to summarize 7, 17, 27, 37, 47, 57, 67, 77, 87, and 97
That is 0 10 ... 80 90 7*10
.
The first part is always 450
, the second part is your number multiplied by 10. This is one line function, you don't need for() loop.