Why is Javascript equating 5 == 8 as true?
Because you are iterating over the statusList
. At first iteration you check if 5 == 8, then moves to else part and inserts 8
in statusList
. Your statusList is = [5, 8]. For next iteration, this becomes true statuslist[i]
will be 8 and 8===8 and your statement - statusList[i] = 123;
will replace last inserted 8
value with 123
. Therefore, your statusList array will have ["5", 123]
.
var statusList = [];
function updateStatusString(x) {
const input = parseInt(x);
if (statusList != null) {
if (statusList.includes(input)) {
const idx = statusList.indexOf(input);
statusList[idx] = 123;
} else {
statusList.push(input);
}
alert(statusList);
}
}
<label> <input type="checkbox" name="Active" value="5" onchange=updateStatusString("5")> "Active"</label>
<label> <input type="checkbox" name="NonActive" value="8" onchange=updateStatusString("8")> "Active"</label>
It looks like the loop was causing your issue.
- You were checking for the existence of
x
, which on the first loop was false - You pushed it to the array
- Second loop, it existed and was replaced with 123
You can dramatically simplify your code by removing one of the if checks, and using array.prototype.includes instead of looping and checking equality.
Edit: Added a third input to demonstrate 123 being added.
var statusList = [];
function updateStatusString(x) {
if (statusList != null) {
if (statusList.includes(x)) {
statusList[statusList.indexOf(x)] = 123;
} else {
statusList.push(x);
}
}
alert(statusList);
}
<label> <input type="checkbox" name="Active" value="5" onchange=updateStatusString("5")> "Active"</label>
<label> <input type="checkbox" name="NonActive" value="8" onchange=updateStatusString("8")> "Active"</label>
<label> <input type="checkbox" name="NonActive" value="8" onchange=updateStatusString("5")> "Active"</label>
first iteration:
since status list is empty you are adding 5 in it,
second iteration:
statulsList = [5]
you are adding 8 so now the statusList value is [5,8] which means also the length is 2,
so we have a third iteration which in this case 8 === 8 .
if you want to have it different save the length of the status list before adding the other item on the list.
var statusList = [];
function updateStatusString(x) {
if (statusList != null) {
if (statusList.length > 0) {
var lengthStat = statusList.length;
for (var i = 0; i < lengthStat; i++) {
if (parseInt(statusList[i]) == parseInt(x)) {
statusList[i] = 123;
} else {
if(! (statusList.indexOf(x) != -1))
statusList.push(x);
}
}
} else {
statusList.push(x);
}
}
alert(statusList);
}
<label> <input type="checkbox" name="Active" value="5" onchange=updateStatusString("5")> "Active"</label>
<label> <input type="checkbox" name="NonActive" value="8" onchange=updateStatusString("8")> "Active"</label>