Domanda

I am trying to make simple JS code to find out the amount a number from 1 to 9 occurs in a given string. I have this Pascal code that works:

Var n,i:longint;
A:array[0..9] of byte;
Begin
 write('Введите число: ');readln(n);
 While n>0 do
  Begin
   A[n mod 10]:=A[n mod 10]+1;
   n:=n div 10;
  End;
  For i:=0 to 9 do
   writeln('The number ',i,' occurs ',A[i],' amount of times');
  readln;
 End.

In JS I ended up with this, but that seems to have a never-ending loop:

function plosh(form) {
    var list = new Array(9);
    var n = form.a.value;
    while (n>0) {
        a = n % 10;
        list[a] = list[a]+1;
        n = n % 10;
    }
    for (var i=0; i<=9; i++)
    {
        alert("Цифра"+i+"встречается"+A[i]+"раз");
    }
}

Would appreicate any help on where I am going wrong with this. Thanks in advance!

È stato utile?

Soluzione

n = n % 10 leaves n unchanged as soon as it's lower than 10, so it will usually never reach 0, hence the endless loop.

The div operator in Pascal makes an integral division.

Change

n = n % 10

to

n = Math.floor( n / 10 );

You also have another problem : you're not properly initializing your array so you're adding 1 to undefined. Fix that like this :

function plosh(form) {
    var a,
        list = [],
        n = form.a.value;
    while (n>0) {
        a = n % 10;
        list[a] = (list[a]||0)+1;
        n = Math.floor( n / 10 );
    }
    for (var i=0; i<=9; i++) {
        console.log("Цифра"+i+"встречается"+A[i]+"раз"); // <- less painful than alert
    }
}

Altri suggerimenti

n:=n div 10;

was translated as:

n = n % 10;

but should be:

n = Math.floor(n / 10);

Edit: Also, you define an array [0..9] in Pascal, which means 10 elements. When you call Array(9) you only create 9 elements.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top