Coffeescript - 使用 "in" 查找子字符串
Coffeescript - Finding substring with "in"
在 Coffeescript 中,以下给出 true
"s" in "asd" # true
但这给出了 false
"as" in "asd" # false
- 这是为什么?
- 超过 1 个字符的字符串会出现这种情况吗?
in
不适合这个任务吗?
x in y
来自 coffeescript 的语法期望 y
是一个数组,或者类似对象的数组。给定一个字符串,它将把它转换成一个字符数组(不是直接的,但它会像数组一样遍历字符串的索引)。
所以你使用 in
:
"as" in "asd"
# => false
等同于
"as" in ["a","s","d"]
# => false
这样就更容易理解为什么 returns 错误。
little book of coffeescript 在 in
上有话要说:
Includes
Checking to see if a value is inside an array is typically done with indexOf(), which rather mind-bogglingly still requires a shim, as Internet Explorer hasn't implemented it.
var included = (array.indexOf("test") != -1)
CoffeeScript has a neat alternative to this which Pythonists may recognize, namely in.
included = "test" in array
Behind the scenes, CoffeeScript is using Array.prototype.indexOf(), and shimming if necessary, to detect if the value is inside the array. Unfortunately this means the same in syntax won't work for strings. We need to revert back to using indexOf() and testing if the result is negative:
included = "a long test string".indexOf("test") isnt -1
Or even better, hijack the bitwise operator so we don't have to do a -1 comparison.
string = "a long test string"
included = !!~ string.indexOf "test"
就我个人而言,我会说按位破解不是很清晰,应该避免。
我会用 indexOf
:
写支票
"asd".indexOf("as") != -1
# => true
或使用正则表达式匹配:
/as/.test "asd"
# => true
或者如果您使用的是 ES6,请使用 String#includes()
在 Coffeescript 中,以下给出 true
"s" in "asd" # true
但这给出了 false
"as" in "asd" # false
- 这是为什么?
- 超过 1 个字符的字符串会出现这种情况吗?
in
不适合这个任务吗?
x in y
来自 coffeescript 的语法期望 y
是一个数组,或者类似对象的数组。给定一个字符串,它将把它转换成一个字符数组(不是直接的,但它会像数组一样遍历字符串的索引)。
所以你使用 in
:
"as" in "asd"
# => false
等同于
"as" in ["a","s","d"]
# => false
这样就更容易理解为什么 returns 错误。
little book of coffeescript 在 in
上有话要说:
Includes
Checking to see if a value is inside an array is typically done with indexOf(), which rather mind-bogglingly still requires a shim, as Internet Explorer hasn't implemented it.
var included = (array.indexOf("test") != -1)
CoffeeScript has a neat alternative to this which Pythonists may recognize, namely in.
included = "test" in array
Behind the scenes, CoffeeScript is using Array.prototype.indexOf(), and shimming if necessary, to detect if the value is inside the array. Unfortunately this means the same in syntax won't work for strings. We need to revert back to using indexOf() and testing if the result is negative:
included = "a long test string".indexOf("test") isnt -1
Or even better, hijack the bitwise operator so we don't have to do a -1 comparison.
string = "a long test string" included = !!~ string.indexOf "test"
就我个人而言,我会说按位破解不是很清晰,应该避免。
我会用 indexOf
:
"asd".indexOf("as") != -1
# => true
或使用正则表达式匹配:
/as/.test "asd"
# => true
或者如果您使用的是 ES6,请使用 String#includes()