循环嵌套 :99乘法表示例
var s = ""; s += "<table>"; for (var i = 1; i < 10; i++) { s += "<tr>"; for (var j = 1; j <= i; j++) { s += "<td>" + i + "*" + j + "=" + i * j + "</td>"; } s += "</tr>"; } s += "</table>"; document.getElementById("dcon").innerHTML = s;
选择排序示例
var iNum = [34, 19, 11, 109, 3, 56]; var temp=0; for (var i = 0; i <= iNum.length-2; i++) { for (var j = i + 1; j <=iNum.length - 1; j++) { if (iNum[i] > iNum[j]) { temp = iNum[j]; iNum[j] = iNum[i]; iNum[i] = temp; } } } for (var a = 0; a < iNum.length; a++) { document.write(iNum[a] + "<br/>"); }
冒泡排序示例
var iNum = [34, 19, 11, 109, 3, 56];
var temp=0;
for (var i = 0; i <= iNum.length-2; i++) {//-2 小于等于等同于小于-1
for (var j =0; j <=iNum.length-1-i; j++) {//-1为了避免下标越界,-x为了让外循环增加一次,内循环参数与比较的元素个数递减
if (iNum[j] > iNum[j+1]) {
temp = iNum[j];
iNum[j] = iNum[j+1];
iNum[j+1] = temp;
}
}
}
for (var a = 0; a < iNum.length; a++) {
document.write(iNum[a] + "<br/>");
}
时间: 2024-11-29 10:08:47