简体   繁体   English

如何使用 Lodash 以相反的顺序迭代数组?

[英]How to iterate over array in reverse order with Lodash?

I want to iterate over an array in reverse order using Lodash.我想使用 Lodash 以相反的顺序迭代数组。 Is that possible?那可能吗?

My code looks like below.我的代码如下所示。

var array = [1, 2, 3, 4, 5];
_.each(array, function(i) {
   _.remove(array, i);
});

When I do _.pullAt(array, 0) new array is [2, 3, 4, 5] .当我做_.pullAt(array, 0)新数组是[2, 3, 4, 5] All array elements shifted to left by 1 position, and current index is pointing to element 3. After next iteration, 3 will get deleted and then 5. After 3rd iteration array contains [2, 4] which I couldn't delete.所有数组元素向左移动 1 个位置,当前索引指向元素 3。下一次迭代后,3 将被删除,然后是 5。第三次迭代后,数组包含[2, 4] ,我无法删除。

If I iterate over the array in reverse order, then this problem won't arise.如果我以相反的顺序遍历数组,则不会出现此问题。 In Lodash, can I iterate over an array in reverse order?在 Lodash 中,我可以以相反的顺序遍历数组吗?

You can use _.reverse available in version 4:您可以使用版本 4 中可用的_.reverse

var array = [1, 2, 3, 4, 5];
array = _.reverse(array)
console.log(array)
//5, 4, 3, 2, 1

See How do I empty an array in JavaScript?请参阅如何在 JavaScript 中清空数组? if you only want that and choose your weapon .如果你只想要那个并选择你的武器

Otherwise, strictly answering the question, to iterate the indices from the length of the array to zero, you could use the "down-to" --> operator 1 .否则,严格回答这个问题,要将索引从数组长度迭代到零,您可以使用“向下到” -->运算符1 But that's not really necessary, even underscore isn't necessary in this case as the .pop function is enough.但这并不是真正必要的,在这种情况下甚至不需要下划线,因为.pop函数就足够了。

 var arr = [1, 2, 3, 4, 5], index = arr.length; while (index --> 0) { console.log(index); arr.pop(); } console.log(arr);

If you're using Lodash like the functions referenced in the question seem to indicate, you could use _.eachRight .如果您使用 Lodash 就像问题中引用的函数似乎表明的那样,您可以使用_.eachRight

 var arr = [1, 2, 3, 4, 5]; _.eachRight(arr, function(value) { console.log(value); arr.pop(); }); console.log(arr);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>


1 The down-to operator doesn't exist and is only a -- decrement followed by a > comparison. 1 down-to 运算符不存在,只是一个--递减后跟一个>比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM