简体   繁体   中英

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. After finding the exact solution to my problem here and the same problem ,I rolled my coffeescript in order to make things happen.

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

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. You will need to use filter if you want to exclude some elements. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM