[英]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.