Skip to content

Instantly share code, notes, and snippets.

@tonyc726
Created May 20, 2014 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonyc726/a06da0afa0d9b2f1740a to your computer and use it in GitHub Desktop.
Save tonyc726/a06da0afa0d9b2f1740a to your computer and use it in GitHub Desktop.
CoffeeScript 学习笔记

《CoffeeScript袖珍手册》小记

@(JavaScript)[CoffeeScript]

CoffeeScript常用编程模式

indexOf(*string*)来检测一个值是否存在于一个数组/字符串中

我们常常会使用indexOf()方法来判断一个值是不是属于一个数组, 但由于IE还没有支持, 我们还是需要做一些兼容性的处理.

var included = (array.indexOf("test") != -1)

许多Python开发者可能已经发现, 在CoffeeScript中使用了 in 来完美解决这个处理过程.

included = "test" in array

在实际实现中, CoffeeScript使用了 Array.prototype.indexOf() 来检测一个值是否存在于一个数组中, 如果不支持这个, 就做降级处理.不幸的是, 这样做意味着in的语法不能对字符串无效.所以对于字串我们还得用回indexOf(), 并同时判断结果是否为-1:

included = "a long test string".indexOf("test") isnt -1

或者我们改进一下, 使用位运算符这样就避免了和 -1 做对比.

string   = "a long test string"
included = !!~ string.indexOf "test"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment