I created an event listener with a button that has a code onclick, but sometimes when I click the button over and over again it returns undefined I set it to return random things from an array. Anyways, I found out that since i put my array.length -1 it sometimes returns -0 or undefined instead of just 0 in the console. What would be the best way for me to fix this?
This is my code the button listener is in the main.js file:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="root">
<div>
<button id="btn1">sleep</button>
</div>
</div>
<script type="module" src="main.js"></script>
</body>
</html>
main.js
import { v1, v2, v3 ,v4 } from './main2.js';
let btn = document.getElementById('btn1');
console.log(v3);
/////////////////////////////////////////////////
btn.addEventListener('click', () => {
console.log(`${v4[Math.round(Math.random() * v4.length -1
)]}`)
})
main2.js
let log = {
One: 'one',
Two: 'two',
Three: 'three',
Four: ['tester1', 'tester2', 'tester3'],
}
export let {One: v1, Two: v2, Three: v3, Four: v4} = log;
console.log(`${v4[Math.round(Math.random() * v4.length -1)]}`);
Is choosing an number between -1 and 3
It should be this
console.log(`${v4[Math.random() * v4.length | 0]}`);
Which choses a number between 0 and 3. Math.random()
returns a number between 0 and 0.9999999999999999999 so Math.random() * v4.length
will return a number between 0 and 3.99999999999999999999
Then | 0
will turn the result into an integer.
| 0
is faster than Math.floor
and more idiomatic. See Using bitwise OR 0 to floor a number