简体   繁体   English

为什么这些代码在重复运行时在JSBin中运行不同?

[英]Why does this code run differently in JSBin on repeated runs?

On JSBin, this code returns a different number each time it's run, but it doesn't here as a Stack Snippet: 在JSBin上,这段代码每次运行时返回一个不同的数字,但它不作为Stack Snippet在这里:

 function prime(num) { var primes = []; var i = 1; while (primes.length <= num) { if (isPrime(i)) { primes.push(i); } i++; } function isPrime(i) { for (var k = 2; k <= Math.sqrt(i); k++) { if (i % k === 0) { return false; } } return true; } return primes.pop(); } console.log(prime(10001)); 

Link to JSbin . 链接到JSbin What shows in the console if you run it repeatedly on JSBin: 如果在JSBin上重复运行,控制台中会显示什么:

在此输入图像描述

If you look at the chrome console, you can see the below warning. 如果查看chrome控制台,可以看到以下警告。 Thats why the loop is disconnected randomly at some stage. 这就是为什么循环在某个阶段随机断开的原因。

Exiting potential infinite loop at line 6. To disable loop protection: add "// noprotect" to your code 在第6行退出潜在的无限循环。要禁用循环保护:在代码中添加“// noprotect”

If you add the line // noprotect on top of your code as below and run it in JSBin, its giving the right answer all the time. 如果你在代码顶部添加// noprotect行并在JSBin中运行它,它会一直给出正确的答案。

// noprotect
function prime(num) {
  var primes = [];
  var i = 1;

  while (primes.length <= num) {
    if (isPrime(i)) {
      primes.push(i);
    }
    i++;
  }

.....

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

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