How to check for undefined type in javascript
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
在javascript中检查
我尝试过几种方法,但没有成功:
1 2 | alert(undefined ==="undefined"); alert(undefined ||"defined"); |
没有什么新鲜事:
1 2 3 4 | // either (val === undefined) // or (typeof val =="undefined") |
使用
这是你说的使用typeof的最好方式。
例子:
1 | alert(typeof variable === 'undefined') |
使用
1 2 3 4 5 6 7 8 9 10 | var x; console.log("x == undefined =>" + (x == undefined)); console.log("typeof x == 'undefined' =>" + (typeof x == 'undefined')); var undefined = 10; // for some reason, browsers allow this! console.log('undefined overwritten to ' + undefined); console.log("x == undefined =>" + (x == undefined)); // this will return false! console.log("typeof x == 'undefined' =>" + (typeof x == 'undefined')); |
1 | var variable2 = variable1 || ''; |
如果变量1未定义,它将设置为"",否则将使用variable1。