如何将变量与未定义进行比较,如果我不知道它们是否存在?(How to compare variables to undefined, if I don’t know whether they exis

编程入门 行业动态 更新时间:2024-10-28 18:33:11
如何将变量与未定义进行比较,如果我不知道它们是否存在?(How to compare variables to undefined, if I don’t know whether they exist? [duplicate])

这个问题已经在这里有一个答案:

如何检查JavaScript中的“未定义”? [重复] 16答案

在JavaScript中,您可以声明一个变量,如果undefined ,则可以检查variable == undefined ; 我知道,但是如果你在记忆中如何比较你还不知道的值呢?

例如,我有一个类,当用户点击一个按钮时创建。 在此之前,这个课程是未定义的 - 它不存在于任何地方; 我该怎么比较呢?

有没有使用try - catch ?

This question already has an answer here:

How to check for “undefined” in JavaScript? [duplicate] 16 answers

In JavaScript you can declare a variable and if it’s undefined, you can check variable == undefined; I know that, but how can you compare a value that you don’t know yet if it’s in memory?

For example, I have a class which is created when the user clicks a button. Before this, the class is undefined — it doesn’t exist anywhere; how can I compare it?

Is there a way without using try–catch?

最满意答案

最好的方法是检查类型 ,因为undefined / null / false在JS中是一件棘手的事情。 所以:

if(typeof obj !== "undefined") { // obj is a valid variable, do something here. }

请注意, typeof总是返回一个字符串,如果该变量根本不存在,则不会生成错误。

The best way is to check the type, because undefined/null/false are a tricky thing in JS. So:

if(typeof obj !== "undefined") { // obj is a valid variable, do something here. }

Note that typeof always returns a string, and doesn't generate an error if the variable doesn't exist at all.

更多推荐

本文发布于:2023-07-22 03:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1216691.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我不   变量   如何将   是否存在   未定义

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!