1/23/13

_.map


Underscore's _.map function can take an object or an array as input, but it always returns an array.

So

_.map({a : 1, b : 4, c : 9}, Math.sqrt)

returns

[1, 2, 3]

instead of

{a : 1, b : 2, c : 3}

alas.. why underscore? WHY?

update: ugg.. it is worse than I thought. Underscore treats objects with a "length" as arrays.

So

var tokenCounts = {"hello" : 5, "world" : 3, "length" : 1, "0" : 4}
var sum = 0
_.each(tokenCounts, function (count) { sum += count })
alert(sum)

shows

4

because it sees a "length" of 1, and therefore uses a for-loop with i going from 0 to length - 1.

as for WHY, it is because some DOM and jQuery functions return things that look like arrays, but are not real arrays, and Underscore wants _.each to work on them "as expected".

I'm not sure what should be done here. I feel like the right answer is: do a better job detecting array-like-objects. Checking for "length" isn't enough. There must be some other indicator...

No comments:

Post a Comment