你想把字符串轉(zhuǎn)換成小寫形式。
使用 JavaScript 的 String 的 toLowerCase() 方法:
"ONE TWO THREE".toLowerCase()
# => 'one two three'
toLowerCase() 是一個(gè)標(biāo)準(zhǔn)的 JavaScript 方法。不要忘了帶圓括號(hào)。
通過下面的快捷方式可以添加某種類似 Ruby 的語(yǔ)法塊:
String::downcase = -> @toLowerCase()
"ONE TWO THREE".downcase()
# => 'one two three'
上面的代碼演示了 CoffeeScript 的兩個(gè)特性:
.prototype 的快捷方式;上面的代碼會(huì)編譯成如下 JavaScript 代碼:
String.prototype.downcase = function() {
return this.toLowerCase();
};
"ONE TWO THREE".downcase();
提示 盡管上面的用法在類似 Ruby 的語(yǔ)言中很常見,但在 JavaScript 中對(duì)本地對(duì)象的擴(kuò)展經(jīng)常被視為不好的。(請(qǐng)看:Maintainable JavaScript: Don’t modify objects you don’t own;Extending built-in native objects. Evil or not?)