【发布时间】:2021-01-28 05:16:30
【问题描述】:
试图创建一个函数,从数组中删除每个数字(就地),除了函数中最后两个参数之间的数字。这些应该留下。 我得到了这个练习:
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);
【问题讨论】:
-
使用反向
for循环(从最后一个索引到 0),以便splice不会影响未来的索引。 -
forEach不尊重从数组中删除元素的时间。这意味着,当您从数组中的index删除一项时,index + 1的下一项将成为index的元素,然后forEach转到index + 1,跳过该项。
标签: javascript arrays