最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Customizing Underscore.js' range() - Stack Overflow

programmeradmin2浏览0评论

Using range() in Underscore I can make something like this:

_.range(10);
>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Can I somehow modify/use that to create a result such as this:

solution();
>> {0: true, 1: true, 2: true, 3: true}

The solution may also include jQuery.

Using range() in Underscore I can make something like this:

_.range(10);
>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Can I somehow modify/use that to create a result such as this:

solution();
>> {0: true, 1: true, 2: true, 3: true}

The solution may also include jQuery.

Share Improve this question edited Oct 12, 2012 at 11:53 phant0m 16.9k6 gold badges51 silver badges84 bronze badges asked Oct 12, 2012 at 11:25 js999js999 2,0834 gold badges26 silver badges34 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

Yes.

var range = _.range(10);
_.map(range, function() { return true; });

jsFiddle.

If you must have an object (the former returns an array), run this on the result...

_.extend({}, range);

jsFiddle.

It's worth mentioning, if you didn't have Underscore or wanted to use jQuery, there are equivalents $.map() and $.extend().

The accepted answer is just fine for the given question, but it should be noted that, as given, it will only work for a range of incrementing integers beginning with zero since it's actually using the index, not the element's value.

Here's another of the many possible solutions. When I need to turn an array into a "lookup hash" I do this:

var range = _.range(10);
var hash = _.object(range, range.map(_.const(true)));

This will take into account the actual values in your source array, which could be numbers or strings in any sequence.

I don't particularly remend this, but if it's possible to be certain that your source range does not contain zero, you could simplify it further, since all values will be truthy:

var hash = _.object(range, range);
发布评论

评论列表(0)

  1. 暂无评论