我可以使用一些我不知道的coffeescript语法来简化这个数组差异代码吗?
first = [{id:1},{id:2},{id:3},{id:4},{id:5}]
second = [{id:3},{id:4},{id:5},{id:6},{id:7}]
first = first.filter (first_element) ->
second = second.filter (second_element) ->
if first_element.id == second_element.id
first_element.remove = second_element.remove = true
return !second_element.remove?
return !first_element.remove?
console.log(first.concat second) # [{id:1},{id:2},{id:6},{id:7}]
答案 0 :(得分:1)
这个转换为完全相同的javascript:
first = [{id:1},{id:2},{id:3},{id:4},{id:5}]
second = [{id:3},{id:4},{id:5},{id:6},{id:7}]
first = first.filter (first_element) ->
second = second.filter (second_element) ->
first_element.remove = second_element.remove = yes if first_element.id is second_element.id
!second_element.remove?
!first_element.remove?
console.log(first.concat second) # [{id:1},{id:2},{id:6},{id:7}]
删除了明确的return
,if
放在了行的末尾。 yes
替换为true
,==
替换为is
。
虽然行不短,但它保留了数组中的对象:
first = first.filter (firstElement) ->
keepFirst = yes
second = second.filter (secondElement) ->
keepFirst = (keepSecond = secondElement.id isnt firstElement.id) and keepFirst
keepSecond
keepFirst
请注意,您不能使用and=
运算符,因为它短暂循环。