Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

referenceerror - How can I compare a non-existing JavaScript object to undefined without getting a Reference Error?

I want to boolean to come out of this expression

(task === undefined);

where task is arbitrary and doesn’t appear in the code at all.

However, when I run this in rhino, I get a reference Error. I WANT TRUE

Why don’t I get true?

I want to check if a particular variable has been defined. How do I do it then if this doesn't work?

question from:https://stackoverflow.com/questions/11380283/how-can-i-compare-a-non-existing-javascript-object-to-undefined-without-getting

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

1 Answer

0 votes
by (71.8m points)

Use this:

(typeof task === "undefined")

When you use (task === undefined), Javascript needs to find the value of task to see if it is the same as undefined, but it can't look up the name because it doesn't exist, giving you the reference error. typeof is special in that it can safely return the type of a name that doesn't exist.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...