Probé este proyecto hace un tiempo e incluso copié y pegué algunas partes de los proyectos de trabajo que tenía guardados. El color de fondo no cambiará y estoy confundido.
const colors = ['red', 'green', 'blue']; const colorIndex = -1; let myFunction = () => { colorIndex += 1; if (colorIndex > colors.length-1) colorIndex = 0; document.body.style.backgroundColor = colors[colorIndex]; } body{ text-align: center; } #btn { margin-top: 25%; } <!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"> <title>Colour Flipper</title> <link rel="stylesheet" href="color.css"> </head> <body> <button id="btn" onclick="myFunction()">Click to change colour</button> </body> <script src="color.js"></script> </html>TypeError no capturado: Asignación a variable constante. Cambiar variable constante
const colorIndex = -1;a
let colorIndex = -1;Use let en lugar de const. No puede reasignar const.
const colors = ['red', 'green', 'blue']; let colorIndex = -1; let myFunction = () => { colorIndex += 1; if (colorIndex > colors.length-1) colorIndex = 0; document.body.style.backgroundColor = colors[colorIndex]; }Este es el Javascript. Inicializas las variables con const. Pero tienes que hacerlo con let o var.
let colors = ['red', 'green', 'blue']; let colorIndex = -1; let myFunction = () => { colorIndex += 1; if (colorIndex > colors.length-1) colorIndex = 0; document.body.style.backgroundColor = colors[colorIndex]; }