鉴于此类数据集
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
我看过很多相似的代码,但它对我来说很合适。
感谢您的帮助!
答案 0 :(得分:4)
这个示例脚本怎么样?使用WebView
检索结果over50s
。
filter()
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
如果我误解了你的问题,请告诉我。我想修改。
答案 1 :(得分:2)
答案很完美,但我想使用reference添加“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.