赫謙小便籤

用CoffeeScript實作Array#list

在寫專案的過程當中想要操作Array,可是在JavaScript中沒有[1, 2, 3].last()這種東西可以用,只好自己擴充啦~

1
2
Array::last = ->
  @[@.length - 1]

這樣就會回傳

1
2
3
Array.prototype.last = function(){
  return this[this.length - 1];
}

然後網路上的高見龍前輩在Slideshare的投影片 http://www.slideshare.net/aquarianboy/coffeescriptrubytuesday 中第160頁也有一些針對字串的擴充:

1
2
3
4
5
String::repeat = (n) -> Array(n + 1).join @
String::downcase = -> @toLowerCase()
String::upcase = -> @toUpperCase()
String::find = (str) -> @indexOf str
String::has = (str) -> (@indexOf str) > 0

其實蠻炫的XD

Comments