admin管理员组

文章数量:1193730

I've a for loop in javascript shown below. How to convert it to lodash for loop? In such scenarios using lodash is advantageous over javascript for loop?

I've not used lodash much. Hence please advice.

for (var start = b, i = 0; start < end; ++i, ++start) {
// code goes here
}

I've a for loop in javascript shown below. How to convert it to lodash for loop? In such scenarios using lodash is advantageous over javascript for loop?

I've not used lodash much. Hence please advice.

for (var start = b, i = 0; start < end; ++i, ++start) {
// code goes here
}
Share Improve this question asked Jul 6, 2015 at 13:09 Temp O'raryTemp O'rary 5,80815 gold badges53 silver badges114 bronze badges 4
  • Why do you need to use lodash here? – Binkan Salaryman Commented Jul 6, 2015 at 13:15
  • Just trying out lodash. Want to explore it and how to use it in different scenarios, – Temp O'rary Commented Jul 6, 2015 at 13:18
  • Check this out: stackoverflow.com/questions/18881487/… – Dänu Commented Jul 6, 2015 at 13:22
  • 1 The only alternative I can think of is eaching a range – megawac Commented Jul 7, 2015 at 3:11
Add a comment  | 

3 Answers 3

Reset to default 13

You can use lodash range
https://lodash.com/docs/4.17.4#range

_.range(5, 10).forEach((current, index, range) => {
    console.log(current, index, range)
})

// 5, 0, [5, 6, 7, 8, 9, 10]
// 6, 1, [5, 6, 7, 8, 9, 10]
// 7, 2, [5, 6, 7, 8, 9, 10]
// 8, 3, [5, 6, 7, 8, 9, 10]
// 9, 4, [5, 6, 7, 8, 9, 10]
// 10, 5, [5, 6, 7, 8, 9, 10]

I will imagine that b = 3 and end = 10 if I run your code and print the variables here is what I will get:

var b = 3;
var end = 10;

for (var start = b, i = 0; start < end; ++i, ++start) {
  console.log(start, i);
}

> 3 0
> 4 1
> 5 2
> 6 3
> 7 4
> 8 5
> 9 6

To perform this with lodash (or underscore) I will first generate an array with range then iterate over it and gets the index on each iteration.

Here is the result

var b = 3;
var end = 10;

// this will generate an array [ 3, 4, 5, 6, 7, 8, 9 ]
var array = _.range(b, end); 

// now I iterate over it
_.each(array, function (value, key) {
  console.log(value, key);
});

And you will get the same result. The complexity is the same as the previous one (so no performance issue).

It seems there is no lodash way for writing loose for loops (those not iterating over a collection), but here is a simplified version of it:

for (var i = 0; i < end - b; i++) {
      var start = i + b;
      // code goes here
}

本文标签: javascriptlodashhow to loop with between a start value and end valueStack Overflow