我有以下Javascript代码,我想要做的基本上是数字1的两倍,并继续根据用户输入。所有代码都可以工作,除了我的for循环。此外,我尝试为“步骤”添加空格,但无论我在document.write语句中放置多少空格,它都不会反映在网页中。感谢您的帮助
var num=1;
function iterations()
{
document.write("<b>Sequence of numbers up to iteration number: </b>"+numIterations+"<br>");
for(var i=1;i<=numIterations;i++)
{
var total=num*2;
if(numIterations<10)
{
document.write("<b>STEP "+i+":</b>"+" "+" "+" "+num+"*2="+total+"<br>");
}
else
{
document.write("<b>STEP "+i+":</b> "+num+"*2="+total+"<br>");
}
num*2;
}
}
var numIterations= prompt("Please enter the upper limit\n\nDo NOT exceed 30");
if(numIterations==null||numIterations>30)
{
document.write("User enter an invalid (out of range) value");
}
else
{
iterations();
}
答案 0 :(得分:1)
你有一个错误:
这句话说:
num*2;
替换为
num*=2;
使用此代码,与上面相同,上面的行更改为num * = 2;
var num=1;
function iterations()
{
document.write("<b>Sequence of numbers up to iteration number: </b>"+numIterations+"<br>");
for(var i=1;i<=numIterations;i++)
{
var total=num*2;
if(numIterations<10)
{
document.write("<b>STEP "+i+":</b>"+" "+" "+" "+num+"*2="+total+"<br>");
}
else
{
document.write("<b>STEP "+i+":</b> "+num+"*2="+total+"<br>");
}
num*=2;
}
}
var numIterations= prompt("Please enter the upper limit\n\nDo NOT exceed 30");
if(numIterations==null||numIterations>30)
{
document.write("User enter an invalid (out of range) value");
}
else
{
iterations();
}
答案 1 :(得分:1)
你需要*=
你的num
变量,所以它每次都会加倍,因为你一直用相同的数字代替它而不工作 - 这样做的简单错误就是不要担心
以下作品:
var num = 1;
function iterations()
{
document.write("<b>Sequence of numbers up to iteration number: </b>"+numIterations+"<br>");
for(var i=1;i<=numIterations;i++)
{
var total=num*2;
if(numIterations<10)
{
document.write("<b>STEP " + i +":</b>"+" "+" "+" "+num+"*2="+total+"<br>");
}
else
{
document.write("<b>STEP " + i +":</b>"+num+"*2="+total+"<br>");
}
num*=2;
}
}
var numIterations= prompt("Please enter the upper limit\n\nDo NOT exceed 30");
if(numIterations==null||numIterations>30)
{
document.write("User enter an invalid (out of range) value");
}
else
{
iterations();
}