过滤咖啡脚本中的记录数组以返回年龄> 50的所有记录
Posted
技术标签:
【中文标题】过滤咖啡脚本中的记录数组以返回年龄> 50的所有记录【英文标题】:Filtering an array of records in coffeescript to return all records with age > 50 【发布时间】:2018-07-10 05:27:05 【问题描述】:鉴于这种数据集
records = [
id: 1, name: "John Smith", age: 49,
id: 2, name: "Jane Brown", age: 45,
id: 3, name: "Tim Jones", age: 60,
id: 4, name: "Blake Owen", age: 78
]
如何过滤记录以返回刚刚超过 50 岁的缩减数组。
说返回数组是
over50s = // something
我查看了很多类似的代码,但它们对我来说非常融合。
感谢您的帮助!
【问题讨论】:
【参考方案1】:这个示例脚本怎么样?使用filter()
检索结果over50s
。
示例脚本:
records = [
id: 1, name: "John Smith", age: 49,
id: 2, name: "Jane Brown", age: 45,
id: 3, name: "Tim Jones", age: 60,
id: 4, name: "Blake Owen", age: 78
]
over50s = records.filter (e) -> e.age >= 50
结果:
[
id: 3, name: 'Tim Jones', age: 60 ,
id: 4, name: 'Blake Owen', age: 78
]
如果我误解了你的问题,请告诉我。我要修改。
【讨论】:
【参考方案2】:答案很完美,但我想使用comprehensions添加“Coffeescript方式”:
over50s = (record for record in records when record.age > 50)
解释:
for record in records
console.log(record)
# This would loop over the records array,
# and each item in the array will be accessible
# inside the loop as `record`
console.log(record) for record in records
# This is the single line version of the above
console.log(record) for record in records when record.age > 50
# now we would only log those records which are over 50
over50s = (record for record in records when record.age > 50)
# Instead of logging the item, we can return it, and as coffeescript
# implicitly returns from all blocks, including comprehensions, the
# output would be the filtered array
# It's shorthand for:
over50s = for record in records
continue unless record.age > 50
record
# This long hand is better for complex filtering conditions. You can
# just keep on adding `continue if ...` lines for every condition
# Impressively, instead of ending up with `null` or `undefined` values
# in the filtered array, those values which are skipped by `continue`
# are completely removed from the filtered array, so it will be shorter.
【讨论】:
谢谢。我最初搜索时看到了这种风格..我如何阅读“记录记录”部分?例如,你碰巧知道第一个“记录”取得了什么成就吗?谢谢 如果你要使用单行,你必须小心你的括号:over50s = (record for record in records when record.age > 50)
。否则,您只是为每个 record
说 over50s = record
。
@muistooshort 很好,我在咖啡壳中测试过,但我只看到了理解的输出,over50s
var 从未设置以上是关于过滤咖啡脚本中的记录数组以返回年龄> 50的所有记录的主要内容,如果未能解决你的问题,请参考以下文章