简体   繁体   English

是否可以操作 Array.prototype.map() 的 index 参数?

[英]Is it possible to manipulate the index parameter of Array.prototype.map()?

I was wondering if it is possible to do a "index--" after deleting an element in an Array while using the map function.我想知道在使用 map 函数时删除数组中的元素后是否可以做一个“索引--”。

example:例子:

arr.map((item, index) => item >= a && item <= b? item : arr.splice(index, 1));

after deleting the element at the said index, the index needs to be "index - 1" for the next iteration.删除该索引处的元素后,下一次迭代的索引需要为“index - 1”。 is it possible to somehow manipulate the index in the map function?是否有可能以某种方式操纵 map 函数中的索引?

Not in any elegant way.不是以任何优雅的方式。 The better option would be to avoid splice entirely, and instead use the new returned array from the an array method only, discarding the old one.更好的选择是完全避免splice ,而是仅使用从数组方法返回的新数组,丢弃旧数组。

If you want to remove items between a and b , use .filter :如果要删除ab之间a项目,请使用.filter

const itemsNotBetweenAAndB = arr.map(item => item >= a || item <= b);

If you had to use splice to mutate the existing array (which I'd recommend against since it's ugly and impure), use a for loop:如果您必须使用 splice 来改变现有数组(我建议不要这样做,因为它丑陋且不纯),请使用for循环:

for (let i = arr.length - 1; i >= 0; i--) {
  if (arr[i] > a && arr[i] < b) {
    arr.splice(i, 1);
  }
}

.map should be used only for creating a new array based on transforming all elements of the original array. .map应该仅用于基于转换原始数组的所有元素来创建新数组。 Since here, it looks like you want to remove elements from the original array without transforming each item, .map isn't appropriate, since it won't help you accomplish the goal.从这里开始,看起来您想从原始数组中删除元素而不转换每个项目, .map不合适,因为它不会帮助您实现目标。

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

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