Do you have to check for null & length or is there a shorter way to verify a non-empty string?
I set the value of a hidden field #thimble on page load using server-side values.
Then in JavaScript I want to act on that value only if it has been populated with some non-empty string.
Is this the most concise way of checking that the value is non-empty?
if ($("#thimble").val() != null && $("#thimble").val().length > 0) {
carryOn();
}
Seems rather 开发者_开发百科long.
An empty string is a falsey value, I wouldn't even bother to check its length.
The following is equivalent to your example:
if ($("#thimble").val()) {
carryOn();
}
A falsey value is a value that produces false when evaluated in Boolean context (such as the condition of an if statement).
Falsey values are:
nullundefinedNaN0""(empty string)false
Remember that a string in Boolean context produces false only when its length is 0, if it has whitespace it still produce true:
Boolean(""); // false
Boolean(" "); // true, whitespace
If by non-empty, you mean anything other than zero-length or whitespace-only , then use $.trim with .length:
if ($.trim($("#thimble").val()).length) {
...
}
if ($("#thimble").val().length) {
carryOn();
}
加载中,请稍侯......
精彩评论