[英]TypeError: obj is undefined Coffeescript
I m trying to iterate an array to find if a property matches some condition and retrieve the indexes where the condition applies and thought of using jquerys map method. 我试图迭代一个数组,以查找一个属性是否匹配某个条件,并检索该条件适用的索引,并考虑使用jquerys map方法。 After finding the exact solution to my problem here and the same problem ,I rolled my coffeescript in order to make things happen.
找到我的问题的精确解后在这里和同样的问题,我转了转的CoffeeScript为了使事情发生。
My object is this : 我的对象是这样的:
newWaypoint = {waypoint:latlon.toString(), legStart:leg.start_location.toString() ,legNumber:legNo.toString()}
and such objects are pushed in a simple array : @newDraggableWaypoints.push newWaypoint
并将此类对象放入一个简单数组中:
@newDraggableWaypoints.push newWaypoint
This is the code thats giving me headeache: 这是让我头痛的代码:
buildNewWaypointsFromDraggable:()->
item=@allLegWaypoints[0]
indexes = $.map(@newDraggableWaypoints, (obj, index) =>
index if obj.legStart is item
)
window.alert indexes.toString()
Why is this message presented ? 为什么会显示此消息? Thank you
谢谢
retrieve the indexes where the condition applies
检索条件适用的索引
no, your map
does retrieve something for every element in the array: index
if the condition is fulfilled and undefined
else. 不,您的
map
确实会为数组中的每个元素检索一些内容:如果条件成立则返回index
,否则undefined
。 You will need to use filter
if you want to exclude some elements. 如果要排除某些元素,则需要使用
filter
。 You might do 你可能会做
indexes = @newDraggableWaypoints.map (obj, index) =>
index if obj.legStart is item
.filter (obj) ->
obj is not undefined
or 要么
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.