检查 JavaScript 中对象是否存在

发布于 2024-10-03 02:58:17 字数 285 浏览 5 评论 0原文

如何在 JavaScript 中验证对象是否存在?

以下有效:

if (!null)
   alert("GOT HERE");

但这会引发错误:

if (!maybeObject)
   alert("GOT HERE");

错误:

maybeObject 未定义。

How do I verify the existence of an object in JavaScript?

The following works:

if (!null)
   alert("GOT HERE");

But this throws an Error:

if (!maybeObject)
   alert("GOT HERE");

The Error:

maybeObject is not defined.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

帅气称霸 2024-10-10 02:58:17

您可以安全地对未定义的变量使用 typeof 运算符。

如果它被赋予了任何值,包括 null,typeof 将返回除 undefined 之外的其他值。 typeof 总是返回一个字符串。

所以

if (typeof maybeObject != "undefined") {
   alert("GOT THERE");
}

You can safely use the typeof operator on undefined variables.

If it has been assigned any value, including null, typeof will return something other than undefined. typeof always returns a string.

Therefore

if (typeof maybeObject != "undefined") {
   alert("GOT THERE");
}
阪姬 2024-10-10 02:58:17

这里有很多半真半假的内容,所以我想我把一些事情说得更清楚了。

实际上,您无法准确判断变量是否存在(除非您想将每隔一行包装到 try-catch 块中)。

原因是 Javascript 有这个臭名昭著的值 undefined ,这显然并不意味着该变量未定义,或者它不存在 undefined !== not Define

var a;
alert(typeof a); // undefined (declared without a value)
alert(typeof b); // undefined (not declared)

因此,存在的变量和不存在的变量都会向您报告 undefined 类型。

至于@Kevin的误解,null == undefined。这是由于类型强制,这也是 Crockford 不断告诉每个不确定此类事情的人始终使用严格相等运算符 === 来测试可能的虚假值的主要原因。 null !== undefined 为您提供了您可能期望的内容。另请注意,foo != null 可以是检查变量是否既不是 undefined 也不是 null 的有效方法。当然你可以明确一点,因为这可能有助于可读性。

如果您将问题限制为检查对象是否存在,typeof o == "object" 可能是一个好主意,除非您不考虑数组对象,因为这也将被报告为object 的类型可能会让您有点困惑。更不用说 typeof null 也会给你 object 这完全是错误的。

您真正应该注意 typeofundefinednullunknown 和其他问题的主要区域是 host对象。他们不值得信任。他们几乎可以自由地做任何他们想做的肮脏的事情。因此,请小心使用它们,如果可以的话请检查其功能,因为这是使用甚至可能不存在的功能的唯一安全方法。

There are a lot of half-truths here, so I thought I make some things clearer.

Actually you can't accurately tell if a variable exists (unless you want to wrap every second line into a try-catch block).

The reason is Javascript has this notorious value of undefined which strikingly doesn't mean that the variable is not defined, or that it doesn't exist undefined !== not defined

var a;
alert(typeof a); // undefined (declared without a value)
alert(typeof b); // undefined (not declared)

So both a variable that exists and another one that doesn't can report you the undefined type.

As for @Kevin's misconception, null == undefined. It is due to type coercion, and it's the main reason why Crockford keeps telling everyone who is unsure of this kind of thing to always use strict equality operator === to test for possibly falsy values. null !== undefined gives you what you might expect. Please also note, that foo != null can be an effective way to check if a variable is neither undefined nor null. Of course you can be explicit, because it may help readability.

If you restrict the question to check if an object exists, typeof o == "object" may be a good idea, except if you don't consider arrays objects, as this will also reported to be the type of object which may leave you a bit confused. Not to mention that typeof null will also give you object which is simply wrong.

The primal area where you really should be careful about typeof, undefined, null, unknown and other misteries are host objects. They can't be trusted. They are free to do almost any dirty thing they want. So be careful with them, check for functionality if you can, because it's the only secure way to use a feature that may not even exist.

睡美人的小仙女 2024-10-10 02:58:17

两种方法:

typeof 用于局部变量

您可以使用 typeof 测试局部对象:

if (typeof object !== "undefined") {}

window 用于全局变量

您可以通过检查 window 对象来测试全局对象(在全局范围内定义的对象):

if (window.FormData) {}

Two ways:

typeof for local variables

You can test for a local object using typeof:

if (typeof object !== "undefined") {}

window for global variables

You can test for a global object (one defined on the global scope) by inspecting the window object:

if (window.FormData) {}
起风了 2024-10-10 02:58:17

您可以使用:

if (typeof objectName == 'object') {
    //do something
}

You can use:

if (typeof objectName == 'object') {
    //do something
}
淡忘如思 2024-10-10 02:58:17

如果这是一个全局对象,您可以使用 if (!window.maybeObject)

If that's a global object, you can use if (!window.maybeObject)

弃爱 2024-10-10 02:58:17

如果您只关心它的存在(是否已声明?),则批准的答案就足够了:

if (typeof maybeObject != "undefined") {
   alert("GOT THERE");
}

如果您关心它是否具有实际值,您应该添加:

if (typeof maybeObject != "undefined" && maybeObject != null ) {
   alert("GOT THERE");
}

As typeof( null ) == "object"

例如 bar = { x: 1, y: 2, z: null}

typeof( bar.z ) == "object" 
typeof( bar.not_present ) == "undefined" 

这样你就可以检查它既不是 null 也不是 undefined,由于如果值不存在加上 && 短路,typeof 不会出错,因此您永远不会遇到运行时错误。

就我个人而言,我建议在某处添加一个助手 fn (并且我们不要信任 typeof() ):

function exists(data){
   data !== null && data !== undefined
}

if( exists( maybeObject ) ){
    alert("Got here!"); 
}

If you care about its existence only ( has it been declared ? ), the approved answer is enough :

if (typeof maybeObject != "undefined") {
   alert("GOT THERE");
}

If you care about it having an actual value, you should add:

if (typeof maybeObject != "undefined" && maybeObject != null ) {
   alert("GOT THERE");
}

As typeof( null ) == "object"

e.g. bar = { x: 1, y: 2, z: null}

typeof( bar.z ) == "object" 
typeof( bar.not_present ) == "undefined" 

this way you check that it's neither null or undefined, and since typeof does not error if value does not exist plus && short circuits, you will never get a run-time error.

Personally, I'd suggest adding a helper fn somewhere (and let's not trust typeof() ):

function exists(data){
   data !== null && data !== undefined
}

if( exists( maybeObject ) ){
    alert("Got here!"); 
}
旧故 2024-10-10 02:58:17

您可以使用“typeof”。

if(typeof maybeObject != "undefined")
    alert("GOT HERE");

You could use "typeof".

if(typeof maybeObject != "undefined")
    alert("GOT HERE");
寻找我们的幸福 2024-10-10 02:58:17

我过去只是在 javascript 中执行 if(maybeObject) 作为 null 检查。

if(maybeObject){
    alert("GOT HERE");
}

因此,只有当 maybeObject - 是一个对象时,才会显示警报。
我的网站上有一个例子。

https://sites.google.com/site/javaerrorsandsolutions/home/javascript -动态复选框

I used to just do a if(maybeObject) as the null check in my javascripts.

if(maybeObject){
    alert("GOT HERE");
}

So only if maybeObject - is an object, the alert would be shown.
I have an example in my site.

https://sites.google.com/site/javaerrorsandsolutions/home/javascript-dynamic-checkboxes

天气好吗我好吗 2024-10-10 02:58:17

该线程很久以前就被打开了。我认为同时使用三元运算符是最简单的选择:

maybeObject ? console.log(maybeObject.id) : ""

The thread was opened quite some time ago. I think in the meanwhile the usage of a ternary operator is the simplest option:

maybeObject ? console.log(maybeObject.id) : ""
蓝眼睛不忧郁 2024-10-10 02:58:17

我刚刚测试了上面的 typeOf 示例,但没有一个对我有用,所以我使用了这个:

    btnAdd = document.getElementById("elementNotLoadedYet");
    if (btnAdd) {
       btnAdd.textContent = "Some text here";
    } else {
      alert("not detected!");
    }

I've just tested the typeOf examples from above and none worked for me, so instead I've used this:

    btnAdd = document.getElementById("elementNotLoadedYet");
    if (btnAdd) {
       btnAdd.textContent = "Some text here";
    } else {
      alert("not detected!");
    }

ゞ记忆︶ㄣ 2024-10-10 02:58:17

除了检查对象/变量是否存在之外,您可能还想提供“最坏情况”输出,或者至少将其捕获到警报中,这样就不会被忽视。

检查、提供替代方案和捕获错误的函数示例。

function fillForm(obj) {
  try {
    var output;
    output = (typeof obj !== 'undefined') ? obj : '';
    return (output);
  } 
  catch (err) {
    // If an error was thrown, sent it as an alert
    // to help with debugging any problems
    alert(err.toString());
    // If the obj doesn't exist or it's empty 
    // I want to fill the form with ""
    return ('');
  } // catch End
} // fillForm End

我创建这个也是因为我传递给它的对象可能是 x 、 xm 、 xm[z] ,如果 xm 不存在, typeof xm[z] 将会失败并出现错误。

我希望它有帮助。 (顺便说一句,我是 JS 新手)

Apart from checking the existence of the object/variable you may want to provide a "worst case" output or at least trap it into an alert so it doesn't go unnoticed.

Example of function that checks, provides alternative, and catch errors.

function fillForm(obj) {
  try {
    var output;
    output = (typeof obj !== 'undefined') ? obj : '';
    return (output);
  } 
  catch (err) {
    // If an error was thrown, sent it as an alert
    // to help with debugging any problems
    alert(err.toString());
    // If the obj doesn't exist or it's empty 
    // I want to fill the form with ""
    return ('');
  } // catch End
} // fillForm End

I created this also because the object I was passing to it could be x , x.m , x.m[z] and typeof x.m[z] would fail with an error if x.m did not exist.

I hope it helps. (BTW, I am novice with JS)

没︽人懂的悲伤 2024-10-10 02:58:17

对我来说,这适用于 DOM 对象:

if(document.getElementsById('IDname').length != 0 ){
   alert("object exist");
}

for me this worked for a DOM-object:

if(document.getElementsById('IDname').length != 0 ){
   alert("object exist");
}
清晨说晚安 2024-10-10 02:58:17
if (n === Object(n)) {
   // code
}
if (n === Object(n)) {
   // code
}
油焖大侠 2024-10-10 02:58:17

您还可以尝试 && 运算符。

key && value

在这种情况下,如果键返回任何不是以下值的值:

  • null
  • NaN
  • 0
  • false
  • 未定义的
  • 空字符串(“”或''或``),

它将返回key,否则它将返回value
换句话说,如果值是 true (存在),则返回键,否则返回值。

You could also try the && operator.

key && value

In this case if the key returns any value that is not:

  • null
  • NaN
  • 0
  • false
  • undefined
  • empty string ("" or '' or ``)

it will return key, else it will return value.
In other words if the value is true (exists) it returns key else it returns value.

水波映月 2024-10-10 02:58:17

如果不存在任何键或 obj,则可以使用它

 if (Object.keys(obj).length !==0){
      Whatever
 }

如果需要验证某个键是否存在,这将验证 Obj 是否存在而不存在任何键 if (Object.keys(obj).includes('键'))

You can use for if not exist any key or obj

 if (Object.keys(obj).length !==0){
      Whatever
 }

This verifies if Obj exist without any key, if you need to verify some existence key if (Object.keys(obj).includes('key'))

想你的星星会说话 2024-10-10 02:58:17

使用 divalignmnt 选项卡式面板将文本框值设置为内联框架的一帧。
因此,首先,在设置值之前,我们需要使用以下代码检查所选选项卡式面板框架是否可用:

Javascript 代码:

/////////////////////////////////////////
<script>

function set_TextID()
            {
                try
                    {
                        if(!parent.frames["entry"])
                            {
                            alert("Frame object not found");    
                            }
                            else
                            {
                                var setText=document.getElementById("formx").value;
                                parent.frames["entry"].document.getElementById("form_id").value=setText;
                            }
                            if(!parent.frames["education"])
                            {
                            alert("Frame object not found");    

                            }
                            else
                            {
                                var setText=document.getElementById("formx").value;
                                parent.frames["education"].document.getElementById("form_id").value=setText;
                            }
                            if(!parent.frames["contact"])
                            {
                            alert("Frame object not found");    

                            }
                            else
                            {
                                var setText=document.getElementById("formx").value;
                                parent.frames["contact"].document.getElementById("form_id").value=setText;
                            }

                        }catch(exception){}
                }

</script>

set Textbox value to one frame to inline frame using div alignmnt tabbed panel.
So first of all, before set the value we need check selected tabbed panels frame available or not using following codes:

Javascript Code :

/////////////////////////////////////////
<script>

function set_TextID()
            {
                try
                    {
                        if(!parent.frames["entry"])
                            {
                            alert("Frame object not found");    
                            }
                            else
                            {
                                var setText=document.getElementById("formx").value;
                                parent.frames["entry"].document.getElementById("form_id").value=setText;
                            }
                            if(!parent.frames["education"])
                            {
                            alert("Frame object not found");    

                            }
                            else
                            {
                                var setText=document.getElementById("formx").value;
                                parent.frames["education"].document.getElementById("form_id").value=setText;
                            }
                            if(!parent.frames["contact"])
                            {
                            alert("Frame object not found");    

                            }
                            else
                            {
                                var setText=document.getElementById("formx").value;
                                parent.frames["contact"].document.getElementById("form_id").value=setText;
                            }

                        }catch(exception){}
                }

</script>
人事已非 2024-10-10 02:58:17

零和空是隐式指针。如果您不进行算术、比较或将“0”打印到屏幕上,则无需实际键入它。其隐含的。正如暗示的那样。出于同样的原因,也不需要 Typeof。手表。

if(obj) console.log("存在");

我没有看到“不”的请求,因为它不包含在内。尽管我喜欢不符合问题的额外内容。让我们保持简单。

zero and null are implicit pointers. If you arn't doing arithmetic, comparing, or printing '0' to screen there is no need to actually type it. Its implicit. As in implied. Typeof is also not required for the same reason. Watch.

if(obj) console.log("exists");

I didn't see request for a not or else there for it is not included as. As much as i love extra content which doesn't fit into the question. Lets keep it simple.

初相遇 2024-10-10 02:58:17
if (maybeObject !== undefined)
  alert("Got here!");
if (maybeObject !== undefined)
  alert("Got here!");
强辩 2024-10-10 02:58:17

认为这样最简单

if(myobject_or_myvar)
    alert('it exists');
else
   alert("what the hell you'll talking about");

Think it's easiest like this

if(myobject_or_myvar)
    alert('it exists');
else
   alert("what the hell you'll talking about");
对风讲故事 2024-10-10 02:58:17

或者,你们都可以开始使用我独有的 exists() 方法,并能够做一些被认为不可能的事情。即:

诸如:exists("blabla"),甚至:exists("foreignObject.guessedProperty.guessNext.propertyNeeded")也是可能的......

Or, you can all start using my exclusive exists() method instead and be able to do things considered impossible. i.e.:

Things like: exists("blabla"), or even: exists("foreignObject.guessedProperty.guessNext.propertyNeeded") are also possible...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文