JavaScript传统for循环实例
以前在学习程序设计中的for循环的经典实例是九九乘法表,现在我们用JavaScript程序重写代码:
Code
for(i=1;i<=9;i++) {
for(j=1;j<=9;j++) {
console.log(i+ '*' +j+ ' = ' + i*j);
}
}
for(i=1;i<=9;i++) {
for(j=1;j<=9;j++) {
console.log(i+ '*' +j+ ' = ' + i*j);
}
}
另一个实例是在屏幕输出*形矩阵图,现在我们用JavaScript在网页上显示9*9矩阵图:
Code
var getIdName = function(idName) {
this.elem = document.getElementById(idName);
return this.elem;
};
var testCase = {
drawRectangle: function(x, y) {
for(i=1;i<=x;i++) {
for(j=1;j<=y;j++) {
elem = getIdName('elem1');
elem.innerHTML += '*';
}
elem.innerHTML += '<br />';
}
elem.innerHTML += '<br />';
},
run: function() {
this.drawRectangle(9, 9);
}
}
window.onload = function() {
testCase.run();
}
var getIdName = function(idName) {
this.elem = document.getElementById(idName);
return this.elem;
};
var testCase = {
drawRectangle: function(x, y) {
for(i=1;i<=x;i++) {
for(j=1;j<=y;j++) {
elem = getIdName('elem1');
elem.innerHTML += '*';
}
elem.innerHTML += '<br />';
}
elem.innerHTML += '<br />';
},
run: function() {
this.drawRectangle(9, 9);
}
}
window.onload = function() {
testCase.run();
}
HTML代码:
Code
<div id="elem1"></div>
<div id="elem1"></div>
这里的HTML代码仅仅是个装载数据的容器哦。
网页显示效果如下所示:
*********
*********
*********
*********
*********
*********
*********
*********
*********