Estaba tratando de aprender javascript para programar sitios web. Ya sabía html y css y pensé en hacer una puerta lógica simple, pero una vez que la construí, no pude hacer que funcionara. este es el documento html con el script a continuación.
<!DOCTYPE html> <html> <body> <p id="logic">xor: 0 or: 0 and: 0</p> <button onclick="thisScript()">script</button> <script> let A = 1 let B = 1 function thisScript() { if ((A == 1 || B == 1)&& !(A == 1 && B == 1)) { let xor = 1 } else { let xor = 0 } if (A == 1 || B == 1) { let or = 1 } else { let or = 0 }; if (A == 1 && B == 1) { let and = 1 } else { let and = 0 }; document.getElementById("logic").innerHTML = `xor: ${xor} or: ${or} and: ${and}` }; </script> </body> </html>Intenté mover el dom dentro de cada una de las declaraciones if/else y aún no funcionó, aún decía que la variable xor no estaba definida
Este es solo un problema de alcance variable, sus variables estaban en el alcance de las declaraciones if , lo que significaba que no eran accesibles a la última línea de código en su función. El siguiente fragmento de código hace que las variables sean globales, pero también funciona el alcance de la función (segundo fragmento). Visite esta página web para obtener más información sobre los ámbitos de JS.
let A = 1 let B = 1 let xor, and, or; function thisScript() { if ((A == 1 || B == 1) && !(A == 1 && B == 1)) { xor = 1 } else { xor = 0 } if (A == 1 || B == 1) { or = 1 } else { or = 0 }; if (A == 1 && B == 1) { and = 1 } else { and = 0 }; document.getElementById("logic").innerHTML = `xor: ${xor} or: ${or} and: ${and}` }; <!DOCTYPE html> <html> <body> <p id="logic">xor: 0 or: 0 and: 0</p> <button onclick="thisScript()">script</button> </body> </html> let A = 1 let B = 1 function thisScript() { let xor, and, or; if ((A == 1 || B == 1) && !(A == 1 && B == 1)) { xor = 1 } else { xor = 0 } if (A == 1 || B == 1) { or = 1 } else { or = 0 }; if (A == 1 && B == 1) { and = 1 } else { and = 0 }; document.getElementById("logic").innerHTML = `xor: ${xor} or: ${or} and: ${and}` }; <!DOCTYPE html> <html> <body> <p id="logic">xor: 0 or: 0 and: 0</p> <button onclick="thisScript()">script</button> </body> </html>