[英]TypeError: obj is undefined Coffeescript
我試圖迭代一個數組,以查找一個屬性是否匹配某個條件,並檢索該條件適用的索引,並考慮使用jquerys map方法。 找到我的問題的精確解后在這里和同樣的問題,我轉了轉的CoffeeScript為了使事情發生。
我的對象是這樣的:
newWaypoint = {waypoint:latlon.toString(), legStart:leg.start_location.toString() ,legNumber:legNo.toString()}
並將此類對象放入一個簡單數組中: @newDraggableWaypoints.push newWaypoint
這是讓我頭痛的代碼:
buildNewWaypointsFromDraggable:()->
item=@allLegWaypoints[0]
indexes = $.map(@newDraggableWaypoints, (obj, index) =>
index if obj.legStart is item
)
window.alert indexes.toString()
為什么會顯示此消息? 謝謝
檢索條件適用的索引
不,您的map
確實會為數組中的每個元素檢索一些內容:如果條件成立則返回index
,否則undefined
。 如果要排除某些元素,則需要使用filter
。 你可能會做
indexes = @newDraggableWaypoints.map (obj, index) =>
index if obj.legStart is item
.filter (obj) ->
obj is not undefined
要么
indexes = @newDraggableWaypoints
.map (obj, index) -> [obj, index]
.filter ([obj, i]) -> obj.legStart is item
.map ([o, index]) -> index
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.