为什么用 !0 而不是 1 或 true 来设置 localStorage.setItem 数据?

why set localStorage.setItem data with !0 instead of 1 or true?

我看到了这个,但不知道这是将某事设置为 true 的首选方式,还是有人只是想装模作样?当使用 localStorage.setItem 将值设置为 true 时,将使用 !0:localStorage.setItem("proddtm", !0);这比使用 1 还是 true 更好?如果是,为什么?

这与使用 true 或 false 没有什么不同,只不过更容易混淆,因此更不理想。

!0 只是花哨的。它被强制转换为布尔类型,其值为true,与常规true 布尔值相同。但是,1 是一个数字,但 !!1 实际上是 true

还得看实际使用的上下文,不过!0true是等价的

存在将值强制转换为布尔值的用例(例如,检查参数时,如 !!someParameter,如果不是 null,则 return 为真,undefined0 或其他虚假值,但这取决于具体情况。)

一个潜在的好处是true不会进一步缩小,但!0可以为您节省几个字节或其他任何东西,但这是绝对是一些微优化,因为我看不出在什么地方使用 true 而不是 !0 会导致代码瓶颈。