复制代码 代码如下:
document.write(cars[0] +
);
document.write(cars[1] +
);
document.write(cars[2] +
);
document.write(cars[3] +
);
document.write(cars[4] +
);
document.write(cars[5] +
);
不过我们这样写
复制代码 代码如下:
for (var i=0; i{
document.write(cars[i]+
);
}
举例:输出1-100的数字
复制代码 代码如下:
for(var i=0;i {
document.write(i+
)
}
for是前测试循环,而且在循环之前能够初始化变量,并且定义循环后要执行的代码,其语法如下
for(inintialization;expression;psot=loop-expression)statement
执行的过程如下:
1.执行initialization语句
2.判断expression是否为true,如果是则是继续,否则终止整个循环体。
3.执行循环体statement代码
4.执行post-loop-expression代码
5.返回第2步操作
for循环最常用的形式是for(var i=0; i它表示循环一共执行n次,非常适合用于已知的循环次数运算。
复制代码 代码如下:
var anumbers = new array();
var smessage = 你输入了:\n;
var itotal = 0;
var vuserinput;
var iarrayindex = 0;
do{
vuserinput = prompt(输入一个数字,或者'0'退出,0);
anumbers[iarrayindex] = vuserinput;
iarrayindex++;
itotal += number(vuserinput);
smessage += vuserinput + \n;
}while(vuserinput != 0) //当输入为0(默认值)时退出循环体
smessage += 总数: + itotal;
document.getelementbyid(xxx).innerhtml=smessage;
以上就是关于javascript中for循环的全部内容了,希望小伙伴们喜欢。
