<script>
//需求:用户决定输出的次数,输出从0-用户指定的数字之间的所有整数
let num = prompt('请输入数字:')
let res = 0;
for (let i = 0; i < num; i++){
res += i
}
console.log(res);
</script>
02-for 循环:用户指定区间
<script>
let num1 = prompt('请指定起始值:');
let num2 = prompt('请指定结束值:');
num1 = parseInt(num1)
num2 = parseInt(num2)
for (let i = num1; i < num2; i++){
document.write(i)}
</script>
03-for 循环 最大最小值案例
<script>
// 需求:用户输入5个数,求出用户输入数字的最大值
// 用户输入数字的行为:要重复5次:用循环解决,循环一次输入1个数
// 如何保证拿到最大值?定义一个 变量 保存最大值,用户输入的数字与变量进行PK
// 赢了:用户输入是最大值,将用户输入的数据放到变量(修改擂主)
// 输入:不管
// 1. 定义一个擂主:保存最大值
// 2. 打擂:5次
let max = Infinity, min = -Infinity; //定义两个最大最小变量值
for (let i = 1; i <= 5; i++){let count = +prompt(`请输入第${i}次的数值`)
if (count > min){
//最大值交换
min = count
}}document.write(`您输入最大的值为${min}`)
</script>
04-for 循环 利用 break 猜数字大小
<script>
// 猜数字游戏
// 1. 随机生成0-100之间整数
let rand = Math.ceil(Math.random() * 100)
// 2. 用户猜测:不确定次数,循环:死循环
// 2.1 获取用户输入数字
for (;;){let user = prompt('请输入0-100的数字')
// 2.2 比较:三种情况(太大了,太小了,猜中了:break)
if (user > rand){alert('你丫的数值太大了')}else if (user < rand){alert('丫的太小了')}else{alert('你总算猜对了')
break;}}
</script>
05-动态循环 树状图
<style>
.box{width: 1200px;height: 350px;border: 1px solid red;margin: 100px auto;display: flex;justify-content: space-evenly;align-items: flex-end;}.box>div{width: 200px;height: 280px;}
</style>
<script>
// 1. 写好静态结构:分析
// 1.1 外部大div样式:弹性布局或者动态布局
// 1.2 通过静态写死1个到2个柱子:找出柱子宽度的规律(定位需要偏移)
// 1.3 注释静态html:找出样式中固定部分(写到类中)和变化部分(JS动态生成到行内样式)
// 2. 接收用户输入的柱子数量
let user = prompt('请输入柱子数量:');
// 3. 计算柱子的宽度
// 4. 输出大盒子的前半部分(添加类样式)
// 5.4 输出柱子:嵌入行内样式,包括宽度、高度、颜色(rgb)
//输出大盒子开启
document.write('<div class="box">');
for (let i = 1; i <= user; i++){
// 5. 循环动态生成小柱子:一次生成1个柱子
let post = 1200 / (2 * user + 1);
// 5.1 宽度固定
// 5.2 高度随机
let height = Math.ceil(Math.random() * 280);
// 5.3 颜色随机
let a = Math.ceil(Math.random() * 200);
let b = Math.ceil(Math.random() * 200);
let c = Math.ceil(Math.random() * 200);
document.write(`
<div style="width:${post}px;height:${height}px;background-color: rgb(${a}, ${b}, ${c});">
</div>
`)}
// 6. 输出大盒子的关闭部分
document.write('</div>');
</script>
</head>
<body>
<!-- <div class="box">
<div></div>
</div> -->
</body>
</html>
双重for循环
<script>
let num = '';
for (let i = 1; i <= 3; i++){
num += '💕';
console.log(num);
console.log(`这是外层循环第${i}次`);
for (let j = 1; j <= 3; j++){console.log(`这是里层循环第${j}次`);}}
</script>