Hola, chicos, soy nuevo en javascript y trato de comprenderlo mejor. Estoy tratando de hacer un proyecto de 8 bolas y actualmente solo para ver si funciona, mostrarlo en la consola, pero todo lo que recibo es que no está definido.
const predictions = ['Ask again later, Better not tell you now, Cannot predict now, Concentrate and ask again']; const btn = document.getElementById('btn') btn.addEventListener('click', function() { console.log(predictions[randomNumber]) }); function randomNumber() { return Math.floor(math.random() * predictions.length) }; body { background: linear-gradient(to right, #06932d, #000000); display: flex; align-items: center; justify-content: center; } #prediction { position: fixed; top: 300px; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href='8-ball.css'rel="stylesheet"> <script defer src="8-ball.js"></script> <title>8 Ball</title> </head> <body> <div id="title"> <h1>Try the Magic 8 Ball!</h1> </div> <div id="btn"> <button>Try Me!</button> </div> <div id="prediction"> <p>text</p> </div> </body> </html>Hay una serie de problemas en su código:
Te falta el paréntesis para llamar a randomNumber aquí:
console.log(predictions[randomNumber()]); Math siempre comienzan con mayúsculas:
return Math.floor(math.random() * predictions.length); Parece que desea que predictions sean una matriz con varios elementos de cadena. En cambio, tiene un solo elemento con comas:
const predictions = ['Ask again later, Better not tell you now, Cannot predict now, Concentrate and ask again'];Con todo arreglado:
function randomNumber() { return Math.floor(Math.random() * predictions.length); } const predictions = [ 'Ask again later.', 'Better not tell you now.', 'Cannot predict now.', 'Concentrate and ask again.' ]; const btn = document.getElementById('btn'); const prediction = document.getElementById('prediction'); btn.addEventListener('click', () => { prediction.textContent = predictions[randomNumber()]; }); body { background: linear-gradient(to right, #06932d, #000000); font-family: monospace; color: white; display: flex; align-items: center; justify-content: center; min-height: 100vh; margin: 0; } #title { font-size: 24px; margin: 0; } #box { display: flex; align-items: center; justify-content: center; flex-direction: column; } #btn { border: 3px solid white; font-family: monospace; background: transparent; padding: 8px 16px; border-radius: 4px; color: white; font-weight: bold; font-size: 24px; margin: 32px 0; } #prediction { font-size: 24px; margin: 0; } <div id="box"> <h1 id="title">Try the Magic 8 Ball!</h1> <button id="btn">Try Me!</button> <p id="prediction"> </p> </div>