[英]How can I build a regex to exclude all, except letters and numbers?
[英]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
删除一个元素,因为array
是arr
引用。
您可以简单地使用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.