gpt4 book ai didi

javascript - JavaScript 中 undefined variable : difference between typeof and not exists

转载 作者:行者123 更新时间:2023-11-28 19:48:45 25 4
gpt4 key购买 nike

我不明白这两种检查变量是否未定义的方法之间的区别:

if (typeof res.locals.user.hashnodes === 'undefined') {
morphemes = 0;
}

if (!res.locals.user.hashnodes) {
morphemes = 0;
}

对我来说,只有第二个选项有效,第一个选项无效。有人知道为什么吗?

(res.locals.user 是我在 Node Js 应用程序中传递的用户设置)。

谢谢!

最佳答案

if (!res.locals.user.hashnodes) 还将检查现有但错误的值。如果您仅使用 !,则 0、false、''、null、'undefined'、[] 将全部计算为 true

( Here's a more thorough list of what evaluates to what )

那么你的本地有什么值(value)?

console.log(typeof res.locals.user.hashnodes)

如果不是“未定义”,这就是您的答案

关于javascript - JavaScript 中 undefined variable : difference between typeof and not exists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23856157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com