There are a variety of places where I need to check if a JavaScript variable is null or empty string so I wrote an extension method that looks like this:
Object.prototype.IsNullOrEmptyString = function()
{
return (this == null || (typeof this === "string" && this.length == 0));
}
I then call it like so:
var someVariable = null;
if (someVariable.IsNullOrEmptyString())
alert("do something");
But that doesn't work because, at the point of evaluation in the if statement, someVariable is null. The error I keep getting is "someVariable is null".
You can see it live here: / (run in Firefox and notice the error console)
Is there anyway to do what I want and have a single extension method check for null and other things at the same time?
There are a variety of places where I need to check if a JavaScript variable is null or empty string so I wrote an extension method that looks like this:
Object.prototype.IsNullOrEmptyString = function()
{
return (this == null || (typeof this === "string" && this.length == 0));
}
I then call it like so:
var someVariable = null;
if (someVariable.IsNullOrEmptyString())
alert("do something");
But that doesn't work because, at the point of evaluation in the if statement, someVariable is null. The error I keep getting is "someVariable is null".
You can see it live here: http://jsfiddle/AhnkF/ (run in Firefox and notice the error console)
Is there anyway to do what I want and have a single extension method check for null and other things at the same time?
Share Improve this question asked Nov 3, 2011 at 15:17 sohtimsso1970sohtimsso1970 3,2865 gold badges30 silver badges39 bronze badges 1- Extending Object is not a good idea. It should be considered "final" – Bakudan Commented Nov 3, 2011 at 15:40
3 Answers
Reset to default 3null
does not have any properties or methods. You have to create a function, and pass the variable, so it can be tested. Note: To test whether a variable is really an empty string, using === ""
is remended.*
function isNullOrEmpty(test) {
return test === null || test === "";
}
var someVariable = null;
if (isNullOrEmpty(someVariable)) alert("Do something");
* about ==
and ===
. The following parisons are true
:
null == undefined
"" == 0;
"" == false
"" ==
Because your variable is not an object, so its not working. Do it this way.
Object.prototype.IsNullOrEmptyString = function(obj)
{
return (obj == null || (typeof this === "string" && this.length == 0));
}
if(Object.IsNullOrEmptyString(null))
alert('yes');
just make it a function call.
function IsEmptyString(value)
{
return (value == null ||
value === "");
}
Here is a fiddle
Edit: consolidated (=== undefined and === null) into (== null)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745671150a4639409.html
评论列表(0条)