I have added a click
event listener to a button. It calls the buttons YES
AND NO
. Basically the indexOf
checks if the value in the variable foto
is in the yesMeetup
array or in the notMeetup
array.
I tried to debug but I always get "You got it" and it's not calling the debugger when I click on NO
button
let foto = Math.floor(Math.random() * 20) + 1;
document.querySelector('.btn').addEventListener('click', verify);
function verify() {
var yesMeetup = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15];
var notMeetup = [16, 17, 18, 19, 20];
var notButton = document.getElementById('no');
var yesButton = document.getElementById('yes');
var decisao = document.getElementById('decisao');
debugger;
if (yesButton) {
if (yesMeetup.indexOf(foto)) {
decisao.textContent = "You got it";
} else if (notMeetup.indexOf(foto)) {
decisao.textContent = "wrong";
}
} else if (notButton) {
if (notMeetup.indexOf(foto)) {
decisao.textContent = "You Gou it";
} else if (yesMeetup.indexOf(foto)) {
decisao.textContent = "Wrong";
}
}
}
IndexOf(Array, Object, Int32) Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. The range extends from a specified index to the end of the array.
The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
An if
statement will evaluate anything passed into it as a boolean.
The only values for which it will not execute the "true" branch are all falsy values: 0
, null
, undefined
, ''
, false
, NaN
.
Array.prototype.indexOf
returns -1
when an element is not present in an array, which is not one of the falsy values and thus your if
condition
if (array.indexOf(element))
will always evaluate as true.
var example = [1,2,3];
if (example.indexOf(4)) {
console.log('still true');
}
You can use a direct comparison to -1
:
var example = [1,2,3];
if (example.indexOf(4) !== -1) {
console.log('this is not logged');
}
Or a newer, a bit cleaner, Array.prototype.includes
:
var example = [1,2,3];
if (example.includes(4)) {
console.log('this is not logged');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With