当我运行下面的javascript代码时,我得到了变量original,结尾为
"1059823647undefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefined0"为什么会发生这种情况?我如何修复它?
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>");发布于 2009-11-30 09:38:50
您使用的是字符串。而是把它们当做数字。JavaScript会将数字的字符串表示形式转换为实际的数字,但仅在需要时...+运算符不需要这样的转换,因为它充当字符串的连接运算符。
因此,此表达式:
Math.round(Math.floor(i/10)*10)+scramble[i%10]将第一个操作数转换为字符串并从scramble数组中追加元素。在前十次迭代中,您不会注意到这一点,因为当i<10第一个表达式的计算结果为0时...但在那之后,您突然在每个置乱元素前面加上了"10“前缀,并尝试访问original索引>= 100...其中没有任何定义。
解决方案:
在使用字符串之前将其转换为数字。
Math.round(Math.floor(i/10)*10)+ Number(scramble[i%10])发布于 2009-11-30 09:36:36
打印undefined是因为您的方程式:
Math.round(Math.round(Math.floor(i/10)*10)+scramble[i%10])是否返回一个超出数组“原始”范围的数字
例如,当i= 10时,您的方程式返回101。
我不完全确定,但我认为你的意思是:
(Math.floor(i/10)*10) + Number(scramble[i%10])https://stackoverflow.com/questions/1817426
复制相似问题