最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript if typeof ='undefined' in trycatch space - Stack Overflow

programmeradmin1浏览0评论

I have code that is wrapped in try/catch block. I use typeof to find out if a variable is defined:

if (typeof (var) == 'string') { 
    //the string is defined
}

However, using this in a try/catch block, jumps to the catch part instead of doing what it is suppoed to do (do something with the string if its defined).

How can I check if a variable is defined without activating an exception?

I have code that is wrapped in try/catch block. I use typeof to find out if a variable is defined:

if (typeof (var) == 'string') { 
    //the string is defined
}

However, using this in a try/catch block, jumps to the catch part instead of doing what it is suppoed to do (do something with the string if its defined).

How can I check if a variable is defined without activating an exception?

Share Improve this question edited Jun 30, 2009 at 11:15 Alex Rozanski 38k10 gold badges69 silver badges69 bronze badges asked Jun 30, 2009 at 11:12 NirNir 25.4k26 gold badges84 silver badges119 bronze badges 3
  • 1 looks like you have a different problem to the one you think you do - post more code – annakata Commented Jun 30, 2009 at 11:20
  • Thanks eveyone for answering! My var was an array item. this was the reason. I defined the array (as empty array) and now it works. The exeption was fired because the array did not exist. – Nir Commented Jun 30, 2009 at 11:32
  • One point: typeof is an operator, not a function. You don't need parentheses around the operand. [This is migrated from my answer as it is not an answer; I believe I had insufficient rep to post a comment at the time] – Tim Down Commented Feb 7, 2013 at 22:55
Add a comment  | 

2 Answers 2

Reset to default 14

'var' is not a valid variable name - it's a keyword.

Apart from that, what you have should be correct.

I would use a direct comparison without 'typeof':

var vvv= 2;
alert( vvv !== undefined );

Be careful, though, to know whether you want to check for truliness (not false, null, undefined, "" or 0), against null, undefined, false or a combination of these.

If you simply want to see that the value has a value, the code I placed above should do.

As a suggestion, I have found this book tremendous: JavaScript - the Good Parts

发布评论

评论列表(0)

  1. 暂无评论