阅读:7658回复:1
JavaScript For 循环JavaScript 循环 如果您希望一遍又一遍地运行相同的代码,并且每次的值都不同,那么使用循环是很方便的。 我们可以这样输出数组的值: 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<cars.length;i++) { document.write(cars[i] + ""); } |
|
沙发#
发布于:2018-08-08 23:06
取长度 l=cars.length
<!DOCTYPE html> <html> <body> <script> cars=["BMW","Volvo","Saab","Ford"]; for (var i=0,l=cars.length; i<l; i++) { document.write(cars[i] + ""); } </script> </body> </html>同时您还可以省略语句 1(比如在循环开始前已经设置了值时): var i=2,len=cars.length; for (; i<len; i++) { document.write(cars[i] + ""); }实例: <!DOCTYPE html> <html> <body> <script> cars=["BMW","Volvo","Saab","Ford"]; var i=2,len=cars.length; for (; i<len; i++) { document.write(cars[i] + ""); } </script> </body> </html>结果: Saab Ford |
|