简体   繁体   English

拼接方法不会从数组中删除项目

[英]Splice method not deleting items out of array

I'm trying to implement a function which takes three arguments(min, max, step)and generates a range of integers from min to max, with the step.我正在尝试实现一个函数,该函数接受三个参数(min、max、step)并生成从 min 到 max 的整数范围,并带有 step。 The first integer is the minimum value, the second is the maximum of the range and the third is the step.第一个整数是最小值,第二个是范围的最大值,第三个是步长。

Here is an example of what it should look like: generateRange(2, 10, 2) should return array of [2,4,6,8,10].下面是它应该是什么样子的示例: generateRange(2, 10, 2) 应该返回 [2,4,6,8,10] 的数组。

I'm using the splice method to remove any existing elements in the array that are greater than the max argument.我正在使用 splice 方法删除数组中大于 max 参数的任何现有元素。

 function generateRange(min, max, step) { var arr = []; var count = min; for (var i = 0; i < max / step; i++) { arr[i] = count; count = count + step; arr[i] > max ? arr.splice(i, 1) : arr[i]; } return arr; } console.log(generateRange(2, 10, 2));

Whenever I console.log my result I get a bunch of commas after the last item...so it looks like this: [2,4,6,8,10, , , , ]每当我console.log我的结果我在最后一项之后得到一堆逗号......所以它看起来像这样:[2,4,6,8,10, , , , ]

It doesn't appear to be deleting the items.它似乎没有删除项目。 What am I missing?我错过了什么? Thanks!谢谢!

The ternary operator is a bit strange, as the expression is not stored.三元运算符有点奇怪,因为表达式没有存储。 It fixes the array by removing too large values.它通过删除太大的值来修复数组。 That works once, but if there is a second time, i will have increased, and by the assignment to arr[i] , the array's length is again as if there had been no splice performed before (except for the undefined value at that i-1 index).这工作一次,但如果有第二次,会增加,并且通过分配给arr[i] ,数组的长度再次好像之前没有执行过splice (除了未定义的值i -1索引)。

It would be better to exit the loop before assigning a value that is outside of the range.分配超出范围的值之前退出循环会更好。 There is no sense in continuing the loop in such a case.在这种情况下继续循环是没有意义的。

So make the count variable your loop variable and condition:所以让count变量成为你的循环变量和条件:

 function generateRange(min, max, step){ var arr = []; for(var count = min; count <= max; count+=step){ arr.push(count); } return arr; } var res = generateRange(2, 10, 2); console.log(res);

A less readable, but shorter ES6 version would be:一个不太可读但更短的 ES6 版本是:

 function generateRange(min, max, step){ return Array.from(Array(Math.floor((max-min)/step)+1), (x,i) => min+i*step); } let res = generateRange(2, 10, 2); console.log(res);

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

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