简体   繁体   English

js 逻辑门的问题

[英]troubles with js logic gates

i was trying to learn javascript in order to program websites i already knew html and css and thought about making a simple logic gate, but once i had built it i couldnt get it to work.我试图学习 javascript 以编写网站,我已经知道 html 和 css 并考虑制作一个简单的逻辑门,但是一旦我构建了它,我就无法让它工作。 this is the html doc with the script below.这是带有以下脚本的 html 文档。

 <!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>

i tried moving the dom inside each of the if/else statements and it still didnt work it still said that the variable xor was undefined我尝试在每个 if/else 语句中移动 dom,但它仍然不起作用它仍然说变量 xor 未定义

This is just a variable scope problem, your variables were scoped to the if statements which meant that they weren't accesible to the last line of code in your function.这只是一个变量作用域问题,您的变量被限定在if语句的范围内,这意味着它们不能被函数中的最后一行代码访问。 The below snippet makes the variables global, but scoping them to the function also works (second snippet).下面的代码片段使变量成为全局变量,但将它们范围限定为函数也有效(第二个代码片段)。 Checkout this webpage for more info on JS scopes.查看此网页以获取有关 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM