在 Javascript 中制作等同于 Rails 的`present?`

Zab*_*bba 5 javascript

在 Rails 中,我们可以.present?检查字符串是否不是 -nil并且包含除空格或空字符串以外的其他内容:

"".present?       # => false
"     ".present?  # => false
nil.present?      # => false
"hello".present?  # => true
Run Code Online (Sandbox Code Playgroud)

我想在 Javascript 中使用类似的功能,而不必为它编写一个函数,例如 function string_present?(str) { ... }

这是我可以用 Javascript 开箱即用还是通过添加到String的原型来做的事情?

我这样做了:

String.prototype.present = function()
{
    if(this.length > 0) {
      return this;
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

但是,我将如何使这项工作:

var x = null; x.present

var y; y.present
Run Code Online (Sandbox Code Playgroud)

Bra*_*d M 4

String.prototype.present = function() {
    return this && this.trim() !== '';
};
Run Code Online (Sandbox Code Playgroud)

如果值为null,则不能使用原型方法进行测试,可以使用函数。

function isPresent(string) {
    return typeof string === 'string' && string.trim() !== '';
}
Run Code Online (Sandbox Code Playgroud)

  • 你如何在值为“null”的变量上调用它? (3认同)