Pranav Garg
Pranav Garg

Reputation: 613

Any idea why this happens in coffeescript

I have the below code in coffeescript after I run these lines the value of str is still "d41d8cd98f00b204". Any thoughts on what I could be doing wrong?

dataDict = {email: "[email protected]", t:213213.213213}
apiFields = ['email', 'password', 'backup_email', 'firstname', 
             'lastname', 'dob', 'username', 'position', 'industry', 
             'institution', 'verificationcode', 'confirmcode', 
             'signuphost', 'responses', 't']

str = "d41d8cd98f00b204"
for ind in apiFields
  str = str + dataDict[ind] if ind in dataDict
console.log(str)

Upvotes: 4

Views: 73

Answers (4)

Petr Skocik
Petr Skocik

Reputation: 60068

I'd do:

append = dataDict[ind]
str = str + append if append

What you do compiles to:

if (__indexOf.call(dataDict, ind) >= 0) str = str + dataDict[ind];

where

__indexOf === [].indexOf //Array.prototype's indexOf

, and Array.prototype's indexOf doesn't work on non-array objects.

Upvotes: 2

mu is too short
mu is too short

Reputation: 434665

From the fine manual:

You can use in to test for array presence, and of to test for JavaScript object-key presence.

in is for checking if an element is in an array (just like you use for ... in to iterate over an array), if you want to test if a key is in an object you'd use of (just like you use for ... of to iterate over an object):

str = str + dataDict[ind] if ind of dataDict
# -------------------------------^^

Upvotes: 2

beautifulcoder
beautifulcoder

Reputation: 11330

I think in only works on arrays, try:

str = str + dataDict[ind] if dataDict[ind]

Upvotes: 2

rjz
rjz

Reputation: 16510

Check the expansion of if ind in dataDict:

if (indexOf.call(dataDict, ind) >= 0) {
  str = str + dataDict[ind];
}

Checking if dataDict.hasOwnProperty(ind) should get this working.

Upvotes: 0

Related Questions