tags:

views:

76

answers:

2

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>");
+2  A: 

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])
pstanton
+1  A: 

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])
Shog9
copied me...... ;)
pstanton
Naw, just spent too long writing the introduction. +1 for brevity! :-)
Shog9