可以'我在javascript代码中找不到错误

Can't find the error in my javascript code

本文关键字:代码 找不到 错误 javascript 我在 可以      更新时间:2023-09-26

这个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++;
}

更改:

for (var item in p) {

至:

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

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

首先,将您的算法放入一个函数中,并将该函数放入一个页面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 =[];行上进行停止点调试,然后单击页面上的链接test开始调试。F10转到另一行,F11进入方法,F8转到下一个停止点。

希望能有所帮助。

只需更改

if (i%item === 0){

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

那么它就会起作用。

jsfiddle

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

// 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);