繁体   English   中英

从数组中排除两个数字之间的所有除外

[英]exclude all except between two numbers from array

试图创建一个函数,从数组中(就地)删除每个数字,除了函数中最后两个参数之间的数字。 那些应该留下。 我得到了这个练习:

https://javascript.info/array-methods

那么为什么这不起作用呢?

 /* * Array excercize Filter range in place. * remove all except between a and b */ "strict" var arr = [5, 3, 8, 1, 0, 11, 13, 100, 72, 80, 30, 22]; function filterRangeInPlace(arr, a, b) { arr.forEach(function(item, index, array) { if ((item < a) || (item > b)) { array.splice(index, 1); } }); } filterRangeInPlace(arr, 11, 30); console.log(arr);

当您从数组中删除一个元素时, forEach函数不考虑。 这意味着当您从index处的数组中删除一项时,数组中index + 1处的下一项成为index处的元素,然后 forEach 移动到index + 1的项,跳过现在位于的项index .

您可以改用while循环来纠正此行为。

 var arr = [5, 3, 8, 1, 0, 11, 13, 100, 72, 80, 30, 22]; function filterRangeInPlace(arr, a, b) { arr.forEach(function(_, index, array) { var item = array[index]; while((item < a) || (item > b)) { array.splice(index, 1); if (index >= array.length) break; item = array[index]; } }); } filterRangeInPlace(arr, 11, 30); console.log(arr);

在您的代码中,当对array变量使用splice时,它也适用于arr值。 因此,如果您删除array上的一个元素,它也会从arr删除一个元素,因为arrayarr引用。

您可以简单地使用Array.filter来代替forEach

 /* * Array excercize Filter range in place. * remove all except between a and b */ "strict" var arr = [5, 3, 8, 1, 0, 11, 13, 100, 72, 80, 30, 22]; function filterRangeInPlace(arr, a, b) { return arr.filter((item) => item >= a && item <= b); } console.log(filterRangeInPlace(arr, 11, 30));

 /* * Array exercise Filter range in place. * remove all except between a and b */ "strict" var arr = [5, 3, 8, 1, 0, 11, 13, 100, 72, 80, 30, 22]; function filterRangeInPlace(arr, a, b) { return arr.filter(function(item) { if ((item < a) || (item > b)) { return item; } }); } arr = filterRangeInPlace(arr, 11, 30); console.log(arr);

暂无
暂无

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

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