javascript lodash:如何在起始值和结束值之间循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31246763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:32:23  来源:igfitidea点击:

lodash : how to loop with between a start value and end value

javascriptloopslodash

提问by Temp O'rary

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

我在 javascript 中有一个 for 循环,如下所示。如何将其转换为 lodash for 循环?在这种情况下,使用 lodash 是否优于 javascript for 循环?

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

我没有经常使用 lodash。因此请指教。

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

采纳答案by IxDay

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

我会想象,b = 3end = 10如果我运行代码,并打印这里的变量是什么,我会得到:

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 rangethen iterate over it and gets the index on each iteration.

要使用 lodash(或下划线)执行此操作,我将首先生成一个数组,range然后对其进行迭代并获取每次迭代的索引。

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).

你会得到同样的结果。复杂性与前一个相同(因此没有性能问题)。

回答by Andrew Luca

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

您可以使用 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]

回答by Binkan Salaryman

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

似乎没有 lodash 的方式来编写松散for循环(那些不迭代集合的循环),但这里是它的一个简化版本:

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