我們可以.present?
檢查一個字符串是不可─nil
,且含有多於空白或空字符串以外的東西:在Rails使得Rails的`現在相當於'在Javascript
"".present? # => false
" ".present? # => false
nil.present? # => false
"hello".present? # => true
我會像JavaScript中的類似功能,而不必爲它編寫功能,就像function string_present?(str) { ... }
這是我可以用Javascript開箱即可或通過添加到String
的原型?
我這樣做:
String.prototype.present = function()
{
if(this.length > 0) {
return this;
}
return null;
}
不過,我將如何使這項工作:
var x = null; x.present
var y; y.present
如果你沒有足夠的「也可能是唯一的空白」的要求,那麼你可以簡單地使用字符串變量在任何布爾語句中(例如'if(myStr){...}'),因爲'null','undefined'和''''是JavaScript中的錯誤值。 – ajp15243
經過進一步的思考,我認爲你不會像'.present?'那樣獲得「好看」的東西,因爲你不能在JavaScript中使用'null.property'。 BradM可能是最好的解決方案。 – ajp15243
看看[如何檢查字符串是否包含字符和空白,而不僅僅是空白?](http://stackoverflow.com/questions/2031085/how-can-i-check-if-string-contains-characters -whitespace-not-just-whitespace) –