检查未定义 [英] Checking for undefined

查看:53
本文介绍了检查未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全感到困惑.我知道这已经被问了一百万遍了.我看过类似的问题:

I am utterly confused. I know this has been asked a million times. And I have looked at questions like:

测试JavaScript中是否存在未定义的内容

现在的问题是,在进行检查时,我发现您可以执行多项操作.

Now the problem is when doing the check I have found multiple things you can do.

我需要检查对象是否为数组,要检查"length"属性是否存在.现在我要用什么?

I need to check if an object is an array, to do that I check if the "length" property is there. Now what one would I use?

 if (obj.length)

 if (obj.length === undefined)

 if (typeof obj.length === "undefined")

if (obj.length == null)

还是其他?

我知道 === 不会进行任何类型转换,并且if语句只是想要一个真实的"或假的"值,这意味着 obj.length 将返回false,但这不是我们想要的.我们现在要定义它.这就是为什么我要进行类型测试.但是哪种方法最好呢?

I understand that === doesn't do any type conversion, and the if statement is just wanting a "truthy" or "falsey" value, meaning obj.length will return false if the length is 0, but that's not what we want. We want to now if it is defined. Which is why I go to type test. But which way is the best?

这是我做过的一些测试.2、3和4工作.

Here are some tests I did. 2, 3 and 4 work.

很抱歉,在这之间的东西.我是在此页面的控制台中进行的.

Sorry for the stuff in between. I was doing it in the console for this page.

推荐答案

简短答案:

if (obj instanceof Array) {
    // obj is an array
}

或者,如果您不知道是否定义了 obj :

Or, if you don't know whether obj is defined or not:

if ((typeof obj !== "undefined") && (obj instanceof Array)) {
    // obj is an array
}

讨论为什么你的不太正确:

To discuss why yours aren't quite right:

obj.anyProperty 将引发 ReferenceError .这会影响您放置的所有四样东西.

obj.anyProperty will throw a ReferenceError if obj is undefined. This affects all four of the things you put.

if(obj.length)的计算结果为false,这不是您想要的.由于长度为0(一个伪造的值),因此错误地将是错误的.如果另一个对象具有 length 属性,这也可能会出现问题.

if (obj.length) will evaluate to false for an empty array, which isn't what you want. Because the length is 0 (a falsy value), it will falsely be inaccurate. This could also have issues if another object has a length property.

如果(obj.length === undefined)通常会正常工作,但由于可以重新定义 undefined ,因此对此不以为然.有人可以通过编写 undefined = obj.length 破坏您的代码.这也会产生假阴性. obj 可能恰好具有一个名为"length"的属性,并且会错误地将其称为数组.

if (obj.length === undefined) will usually work, but it's frowned upon because undefined can be redefined. Someone could break your code by writing undefined = obj.length. This can also create false negatives; obj could happen to have a property called "length" and it would falsely call it an array.

如果(typeof obj.length ==="undefined")可以正常工作,但可以检测到与上述相同的假阴性.

if (typeof obj.length === "undefined") works fine, but could detect the same false negatives as the above.

if(obj.length == null)可以正常工作,但具有与上述相同的错误.在双等号( == )中,它匹配 null undefined .

if (obj.length == null) will work okay, but has the same bugs as above. In a double-equals (==), it matches null and undefined.

这篇关于检查未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆