Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 views
in Technique[技术] by (71.8m points)

javascript - Checking for undefined

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

Test if something is not undefined in JavaScript

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

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)

or

 if (obj.length === undefined)

or

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

or

if (obj.length == null)

or something else?

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?

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

enter image description here

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Short answer:

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

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 will throw a ReferenceError if obj is undefined. This affects all four of the things you put.

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.

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.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...