我对这个全局变量有疑问。它从不执行 If 语句,即使它为真。
HTML:
<p onclick="change(this)">Click</p>
<p onclick="change2(this)">Click</p>
JavaScript:
var status = false;
localStorage.setItem("status", status);
function change(obj) {
var status = localStorage.getItem("status");
var status = true;
localStorage.setItem("status", status);
}
function change2(obj) {
var status = localStorage.getItem("status");
alert(status)
if (status == true) {
alert("The code works");
} else {
alert("The code doesn't work");
警报(状态)返回 true,但紧接着,我得到“代码不起作用”。我真的很困惑这个问题。任何帮助将不胜感激!
最佳答案
来自documentation :
localStorage.setItem("status", status);
将 DOMString 添加为键和值那是一个 UTF-16 字符串。
keyName
A DOMString containing the name of the key you want to create/update.
keyValue
A DOMString containing the value you want to give the key you are creating/updating.
由于 JavaScript 已经使用了这样的字符串,因此直接映射 DOMString 到 String。
所以你在这里比较一个字符串和一个 bool 值
:
if (status == true) {
相当于:
if ("true" == true) {
在数值转换后将 NaN
与 1
进行比较(true
可转换为编号
)。
因此,作为解决方法,您可以比较字符串:
if (status === "true") {
关于javascript - 如果从不执行,即使它是真的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48291686/