0

这个 js 程序应该显示前 100 个素数,但它每次都崩溃,我找不到错误!有人可以指出我调试 js 代码的最佳方法吗?!谢谢!

// initialisation of the array p holding the first 100 prime numbers
var p = [];

// set the first prime number to 2
p.push(2);

// find the first 100 prime numbers and place them in the array p
var i = 3;
while (p.length < 100) {
    var prime = true;
    loop:
    for (var item in p){
        if (i%item === 0){
            prime = false;
            break loop;
        }
    }
    if (prime)
        p.push(i);
    i = i + 2;
}

// display the first 100 prime numbers found
var i=1;
for (var item in p){
    document.writeln(i,item);
    i++;
}
4

4 回答 4

2

改变:

for (var item in p) {

到:

for (var i = 0; i < p.length; i++) {
    item = p[i];

for-in迭代对象或数组的键,而不是值。

于 2013-06-27T12:42:59.097 回答
1

首先,把你的算法放到一个函数中,然后把这个函数放到一个页面html中。像:

<html>
<head>
<script>

function test(){
// initialisation of the array p holding the first 100 prime numbers
var p = [];

// set the first prime number to 2
p.push(2);

// find the first 100 prime numbers and place them in the array p
var i = 3;
while (p.length < 100) {
    var prime = true;
    loop:
    for (var item in p){
        if (i%item === 0){
            prime = false;
            break loop;
        }
    }
    if (prime)
        p.push(i);
    i = i + 2;
}

// display the first 100 prime numbers found
var i=1;
for (var item in p){
    document.writeln(i,item);
    i++;
}
}

</script>
</head>
    <body>
    <a onmouseclick="test()">test</a>
    </body>
</html>

然后在 Chrome 或 Firefox 中打开此页面。

按 F12 打开调试面板。然后转到 Sources 标签,在左侧视图中选择您的页面(例如:test.html)并在该行上进行停止点调试,var p =[];然后单击页面上的链接测试开始调试。F10 转到另一行,F11 进入方法,F8 转到下一个停止点。

希望有帮助。

于 2013-06-27T12:46:42.550 回答
1

只是改变

if (i%item === 0){

if (i % p[item] == 0){

那么它将起作用。

jsfiddle

于 2013-06-27T13:34:47.367 回答
0

这是最终工作代码的样子:

// initialisation of the array p holding the first 100 prime numbers
var p = [];

// set the first prime number to 2
p.push(2);

// find the first 100 prime numbers and place them in the array p
var i = 3;
var item;
var prime;
while (p.length < 100) {
    prime = true;
    for (item in p){
        if (i%p[item] === 0){
            prime = false;
            break;
        }
    }
    if (prime)
        p.push(i);
    i = i + 2;
}

// display the first 100 prime numbers found
var s = "";
for (item in p){
    if (item != p.length - 1){
        s = s + p[item] + ",";
    }
    else{
        s = s + p[item];
    }
}
alert(s);
于 2013-06-27T16:18:37.913 回答