I am using jQuery to loop through an array and comparing each value with a model’s user id. I will only display a specific text if a match is found.
$.each current_user.get('following_ids'), (i, e) =>
console.log(@model.get('user')._id == e)
if @model.get('user')._id == e
@is_following = true
//break from loop if condition is met
return false
else
@is_following = false
//else continue looping through
return true
if @is_following
$(@el).find('.user_info .follow a').text "following"
else
$(@el).find('.user_info .follow a').text "follow"
However my code is not working, it always returns me “follow” text. What am I doing wrong here?
Presumably
current_user.get('following_ids')is some sort of array of IDs. Two possibilities immediately come to mind:current_user.get('following_ids')doesn’t contain@model.get('user')._idso everything is working as expected.following_idsis an array of strings and_idis a number or vice versa.Option 2 needs a little more explanation: CoffeeScript’s
==is converted to JavaScript’s===so1 == '1'is false in CoffeeScript but true in JavaScript. This does make 2 a hidden and possibly surprising variant of 1 but it is special enough to be its own case.Consider this simplified analogue of your situation:
You’ll get
falseout of that because2 == '2'isfalseis CoffeeScript: http://jsfiddle.net/ambiguous/YsstH/But, if we fix the types:
Then we get the
trueresult that we’re expecting: http://jsfiddle.net/ambiguous/CxHXu/In any case, since you’re using Backbone, you have Underscore so you could just use
_.any:or better:
You’d still have to sort out the type problem though.