代码之家  ›  专栏  ›  技术社区  ›  crimsonpython24

React/Javascript比较运算符不工作

  •  0
  • crimsonpython24  · 技术社区  · 4 年前

    不知何故,我无法让我的比较运算符工作。我有以下代码:

    function handleNotifClickRemind(key) {
      localStorage.setItem('no_remind_change_pwd', true);
      notification.close(key);
    }
    
    // ...
    
    <Button outline size="small" onClick={() => handleNotifClickRemind(key)}>
      Dont remind me
    </Button>
    
    // ...
    
    console.log(localStorage.getItem('no_remind_change_pwd'));
    function another_func(data) {
      if (localStorage.getItem('no_remind_change_pwd') != true) {
        openNotification('topRight');
      }
    }
    

    当我点击“不要提醒我”按钮时, handleNotifClickRemind 因为第三部分的日志输出打印 true . 然而, openNotification 仍在触发。有人能帮忙吗?

    另外,我没有初始化值,我只是让 no_remind_change_pwd 不能为空。

    2 回复  |  直到 4 年前
        1
  •  2
  •   Chuck    4 年前

    在localstorage中保存的都是字符串。 所以你在比较 "true"!=true true .

    如果你想比较这个值,你可以像下面这样使用。 JSON.parse(localStorage.getItem('no_remind_change_pwd')) != true

    也就是说,以下是

    console.log(JSON.parse("true") === true)
        2
  •  1
  •   Satish Chandra Gupta    4 年前
    1. 使用三重比较运算符(如 === !== .
    2. localStorage.getItem() 以字符串格式返回数据,因此如果要与某个布尔值进行比较,请首先将其转换为布尔值。由 Boolean(localStorage.getItem('no_remind_change_pwd')) .

    function another_func(data) {
      if (Boolean(localStorage.getItem('no_remind_change_pwd')) !== true) {
        openNotification('topRight');
      }
    }

    希望这能澄清你的理解。