以下为js语句的案例题,虽然简单,但是里面涉及到语句的嵌套,多个参数,需要好好分析。
1、求出1-100之间所有奇/偶数之和
<script>
var sum = 0;
for (var i = 0; i <= 100; i++) {
if (i % 2 == 0) {
sum += i;
i++;
}
}
console.log(sum); //2550
</script>
2、九九乘法表
<script>
for (var x = 1; x <= 9; x++) {//外层循环决定行的数量
for (var y = 1; y <= x; y++) {//内层循环决定列的数量
document.write(y + "*" + x + "=" + y * x + "  ");
}
document.write("<br>");//添加换行
}
</script>
3、写出1000以内的水仙花数
<script>
var a, b, c, i;
for (i = 100; i < 1000; i++) {
a = parseInt(i / 100);
b = parseInt((i - a * 100) / 10);
c = parseInt(i - a * 100 - b * 10);
if (a * a * a + b * b * b + c * c * c == i) {
document.write(i + "<br>");
}
}
</script>
4、实现5角星图形
<script>
for (var i = 1; i < 5; i++) { //控件行
for (var n = 1; n <= 4 - i; n++) {
document.write(" ");
}
//输出一行*
for (var y = 1; y <= 2 * i - 1; y++) {
document.write("*");
}
document.write('<br>');
}
</script>
</body>
5、点击按钮让box在隐藏与显示之间来回的切换
<body>
<input type="button" id="btn" style="background-color: hotpink;" value="按钮">
<div style=" 100px;height: 100px;background:greenyellow;display: -none;" id="box"></div>
<script>
window.onload = function () {
var btn = document.getElementById('btn');
var box = document.getElementById('box');
var on = 'block';
btn.onclick = function () {
if (on == 'none') {
box.style.display = 'block';
on = 'block';
} else {
box.style.display = 'none';
on = 'none';
}
}
}
</script>
</body>