John Stimac
John Stimac

Reputation: 5491

Why is the result of my calculation undefined?

when I run the javascript code below, I get the variable original as ending as

"1059823647undefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefined0"

why is this happening and how can i fix it?

original="012345678901234567890";
document.write("<textarea>");
document.write(original);
document.write("</textarea>"+"<br>");

/* scramble */
var scramble='1059823647';
scramble=scramble.split('');

var scrambled=new Array();

original=original.split('');

for(i=0;i<original.length;i++){
  if(Math.round(Math.round(Math.floor(i/10)*10)+10)>=original.length){
    scrambled[i]=original[i];
  }else{
    scrambled[i]=original[Math.round(Math.round(Math.floor(i/10)*10)+scramble[i%10])];
  }
}

original='';

for(i=0;i<scrambled.length;i++){
  original+=scrambled[i];
}

document.write("<textarea>");
document.write(original);
document.write("</textarea>"+"<br>");

Upvotes: 1

Views: 1189

Answers (2)

Shog9
Shog9

Reputation: 159628

You're working with strings. But treating them like numbers. JavaScript will convert a string representation of a number to an actual number, but only when it needs to... And the + operator doesn't require such a conversion, as it acts as the concatenation operator for strings.

Therefore, this expression:

Math.round(Math.floor(i/10)*10)+scramble[i%10]

...is converting the first operand into a string and appending an element from the scramble array. You don't notice this for the first ten iterations, since when i<10 the first expression evaluates to 0... But after that, you're suddenly prefixing each scramble element with "10", and trying to access original indexes >= 100... of which there are none defined.

Solution:

Convert your strings to numbers before using them.

Math.round(Math.floor(i/10)*10)+ Number(scramble[i%10])

Upvotes: 0

pstanton
pstanton

Reputation: 36640

undefined is being printed because your equation:

Math.round(Math.round(Math.floor(i/10)*10)+scramble[i%10])

is returning a number outside of the range of your array "original"

eg when i = 10, your equation returns 101.

I'm not entirely sure but i think what you mean to do is this:

(Math.floor(i/10)*10) + Number(scramble[i%10])

Upvotes: 3

Related Questions