简体   繁体   English

使用接头时为什么我的功能不能正常工作?

[英]Why won't my function work when I use splice?

I am trying to write a function which should calculate all prime numbers up to an input parameter and return it. 我正在尝试编写一个函数,该函数应该计算直至输入参数的所有素数并返回它。 I am doing this for practice. 我这样做是为了练习。

I wrote this function in a few ways but I was trying to find new ways to do this for more practice and better performance. 我以几种方式编写了此函数,但我试图寻找新的方法来执行此操作,以进行更多的练习和更好的性能。 The last thing I tried was the code below: 我尝试的最后一件事是下面的代码:

 function primes(num){ let s = []; // sieve for(let i = 2; i <= num; i++){ s.push(i); } for(let i = 0; i < s.length; i++) { for(let j = s[i]*s[i]; j <= num;) { //console.log(j); if(s.indexOf(j)!= -1){ s.splice(s.indexOf(j), 1, 0); } j+=s[i]; } } s = s.filter(a => a != 0); return s; } console.log(primes(10)); 

The problem is that when I run this in a browser it keeps calculating and won't stop and I don't know why. 问题是,当我在浏览器中运行它时,它会不断计算并且不会停止,而且我也不知道为什么。

Note: when I comment out the splice and uncomment console.log(j); 注意:当我注释掉splice和取消注释时, console.log(j); everything works as expected and logs are the things they should be but with splice , the browser keep calculating and won't stop. 一切都按预期工作,日志是应有的内容,但有了splice ,浏览器就会继续计算,不会停止。

I am using the latest version of Chrome but I don't think that can have anything to do with the problem. 我使用的是最新版的Chrome,但我认为这与问题无关。

Your problem lies in this line: 您的问题在于此行:

s.splice(s.indexOf(j), 1, 0);

Splice function third argument contains elements to be added in place of the removed elements. Splice函数的第三个参数包含要添加的元素,以代替已删除的元素。 Which means that instead of removing elements, you are swapping their values with 0's, which then freezes your j-loop. 这意味着您无需删除元素,而是将它们的值交换为0,从而冻结了j循环。 To fix it, simply omit third parameter. 要解决此问题,只需省略第三个参数。

 function primes(num){ let s = []; // sieve for(let i = 2; i <= num; i++){ s.push(i); } for(let i = 0; i < s.length; i++) { for(let j = s[i]*s[i]; j <= num;) { //console.log(j); if(s.indexOf(j)!= -1){ s.splice(s.indexOf(j), 1); } j+=s[i]; } } return s; } console.log(primes(10)); 

Your problem is in this loop: 您的问题出在以下循环中:

for(let j = s[i]*s[i]; j <= num;)

This for loop is looping forever because j is always less than or equal to num in whatever case you're testing. 此for循环将永远循环,因为无论您要测试哪种情况, j始终小于或等于num It is very difficult to determine exactly when this code will start looping infinitely because you are modifying the list as you loop. 确切确定此代码何时开始无限循环非常困难,因为您在循环时正在修改列表。

In effect though, the splice command will be called setting some portion of the indexes in s to 0 which means that j+=s[i] will no longer get you out of the loop. 但是实际上,将调用splice命令将s索引的某些部分设置为0,这意味着j+=s[i]将不再使您跳出循环。

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

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