循环、函数、对象——js基础练习

目录

一、循环练习

1.1 取款机案例

1.2 九九乘法表

1.3 根据数据生成柱形图

1.4 冒泡排序

1.6综合大练习

二、函数

2.1 转换时间案例

三、对象

1. 遍历数组对象

2. 猜数字游戏

3. 生成随机颜色

 4. 学成在线页面渲染案例

一、循环练习

1.1 取款机案例

        // 准备一个总的金额
        let sum = 1000
        while (true) {
            let op = +prompt (`
            请选择您的操作:
                1.取款
                2.存款
                3.查看余额
                4.退出
            `)
            // 如果用户输入的 4,则退出循环,break
            if (op === 4) {
                break
            }
            // 根据输入做操作
            switch (op) {
                case 1:
                    let qu = +prompt('取款')
                    sum = sum - qu
                    break
                case 2:
                    let cun = +prompt('存款')
                    sum = sum + cun
                    break
                case 3:                   
                    alert(`您的余额是${sum}`)
                    break
            }          
        }  

1.2 九九乘法表

    <style>
        span{
            display: inline-block;
            height: 25px;
            line-height: 25px;
            width: 100px;
            padding: 5px 10px;
            /* text-align: left; */
            border: 1px solid #000;
            margin: 2px;
            border-radius: 5px;
            box-shadow: 2px 2px 2px rgba(255, 192, 203, .4);
        }
    </style>
</head>
<body>  
    <script>     
        for (let i = 1; i <= 9; i++) {
            for(let j = 1; j <= i; j++){
                document.write(`<span>${j} * ${i} = ${i * j}</span>`)
            }
            // 进行换行显示
            document.write('<br>')
        }
    </script>

1.3 根据数据生成柱形图

结构样式创建如下代码:

        使用一个box 盒子,设置左及下边框,然后添加四个子元素,每个元素包含span和h4,使用flex布局使得div在box中沿x轴平分剩余空间,y轴与底部对齐排列,然后也为div设置flex布局,使得,span和h4分散在div两端。

    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            display: flex;
            width: 700px;
            height: 300px;
            border-left: 1px solid pink;
            border-bottom: 1px solid pink;
            margin: 50px auto;
            justify-content: space-around;
            align-items: flex-end;
            text-align: center;
        }

        .box>div {
            display: flex;
            width: 50px;
            background-color: pink;
            flex-direction: column;
            justify-content: space-between;
        }

        .box div span {

            margin-top: -20px;
        }

        .box div h4 {
            margin-bottom: -35px;
            width: 70px;
            margin-left: -10px;
        }
    </style>
</head>

<body>
    <div class="box">
        <div style="height: 123px;">
            <span>123</span>
            <h4>第1季度</h4>
        </div>
        <div style="height: 156px;">
            <span>156</span>
            <h4>第2季度</h4>
        </div>
        <div style="height: 120px;">
            <span>120</span>
            <h4>第3季度</h4>
        </div>
        <div style="height: 210px;">
            <span>210</span>
            <h4>第4季度</h4>
        </div>

    </div>

 

最终代码:

    <style>
        * {
            padding: 0;
            margin: 0;
        }
        .box {
            display: flex;
            width: 700px;
            height: 300px;
            border-left: 1px solid pink;
            border-bottom: 1px solid pink;
            flex-direction: row;
            justify-content: space-around;
            align-items: flex-end;
            text-align: center;
        }
        .box > div {
            display: flex;
            width: 50px;
            background-color: pink;
            flex-direction: column;
            justify-content: space-between;
        }
        .box div span {
            margin-top: -20px;
        }
        .box div h4 {
            width: 70px;
            margin-bottom: -35px;
            margin-left: -10px;
        }
        
    </style>
</head>
<body>       
    <script>    
        let arr = [] 
        // 1.四次弹窗效果
        for (let i = 1; i <= 4; i++) {
            arr.push(prompt(`请输入第${i}季度的数据`))
        }
        // 盒子开头
        document.write(`<div class="box">`)
        // 盒子中间 利用循环的形式  跟数组有关系
        for (let i = 0; i < arr.length; i++) {
            document.write(`
            <div style="height: ${arr[i]}px;">
                <span>${arr[i]}</span>
                <h4>第${i + 1}季度</h4>
            </div>
            `)
        }  
        // 盒子结尾
        document.write(`</div>`)
    </script>
</body>

1.4 冒泡排序

        // 转为升序排列
        let arr = [5, 4, 3, 2, 1]
        for (let i = 0; i < arr.length - 1; i++) {
            for (let j = 0; j < arr.length - i - 1; j++) {
                // 开始交换,前提是前一个数大于后一个数才交换
                if (arr[j] > arr[j + 1]) {
                    // 交换两个变量
                    let temp = arr[j]
                    arr[j] = arr[j + 1]
                    arr[j + 1] = temp
                }
            }
        }
        console.log(arr);

1.5 找到数组中某个元素的下标,没有就打印-1

找出数组中 元素为10的下标,有则打印该下标,没有则打印-1

注意,可以设置储存结果的变量值为-1,有该元素时该变量值变为该元素的下标

        arr = [88,20,30,100,50]
        let re = -1 //用于储存结果,默认没有
        for (let i = 0; i < arr.length; i++) {
            if (arr[i] === 10) {
                re = i //如果找到就把当前索引号赋值给re, 如果没有找到,则默认是-1
                break //找到就退出
            }
        }
        console.log(re);

1.6综合大练习

注意因为无效不放入数组,故可以根据数组的长度来判断循环终止条件 

// 定义空数组
let arr = []
while (arr.length < 5) {
    // 输入年龄
    let age = +prompt('输入第${arr.length + 1}个有效年龄(0-100)')
    // 判断是否有效
    if (age >= 0 && age <= 100) {
        // 添加到数组中
        arr.push(age)
    }
}
console.log(arr);
let total = 0
let max = arr[0]
let min = arr[0]
for (let i = 0; i < arr.length; i++) {
    if (arr[i] >= 18) {
        console.log(`成年人的年龄有${arr[i]}`);
    }
    arr [i] > max ? max = arr[i] : max
    arr [i] < min ? min = arr[i] : min
    total += arr[i]
}
let ave = total / arr.length
console.log(`总年龄为${total},平均年龄为${ave}`);
console.log(`最大值为${max},最小值为${min}`);

二、函数

2.1 转换时间案例

    //用户输入 
    let second = +prompt('请输入秒数')
    // 封装函数
    function getTime(t) {
        // 转换
        let hour = parseInt(t / 60 / 60 % 24) 
        let minu = parseInt(t / 60 % 60)
        let sec = parseInt(t % 60)
        // 补0
        hour = hour < 10 ? '0' + hour : hour
        minu = minu < 10 ? '0' + minu : minu
        sec = sec < 10 ? '0' + sec : sec
        return `转换之后为${hour}小时${minu}分钟${sec}秒`
        // console.log(`${t}转换为${hour}小时${minu}分${sec}秒`);
    }
    let str = getTime(second)
    console.log(str);

三、对象

1. 遍历数组对象

 

 表格结构及样式代码:

    <style>
        
        table {
            width: 600px;
            text-align: center;
            border-collapse: collapse;
        }
        table,
        th,
        td {
            border: 1px solid #ccc;
        }
        caption {
            font-size: 18px;
            margin-bottom: 10px;
            font-weight: 700;
        }
        table tr {
            height: 40px;
            cursor: pointer;
        }
        table tr:first-child {
            background-color: #ddd;
        }
        table tr:not(:first-child):hover {
            background-color: #eee;
        }       
    </style>
</head>
<body>     
    <h2>学生信息</h2>
    <p>将数据渲染到页面中...</p>

    <table>
        <caption>学生列表</caption>
        <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>家乡</th>
        </tr>
        <tr>
            <td>1</td>
            <td>小明</td>
            <td>18</td>
            <td>男</td>
            <td>河北省</td>
        </tr>
        <tr>
            <td>1</td>
            <td>小明</td>
            <td>18</td>
            <td>男</td>
            <td>河北省</td>
        </tr>
        <tr>
            <td>1</td>
            <td>小明</td>
            <td>18</td>
            <td>男</td>
            <td>河北省</td>
        </tr>     
    </table>

最终渲染的 js 代码:

<body>     
    <h2>学生信息</h2>
    <p>将数据渲染到页面中...</p>
    <table>
        <caption>学生列表</caption>
        <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>家乡</th>
        </tr>
    <!-- script写到这里 -->
    <script>   
        // 数据准备
        let students = [
            {name: '小明', age: 18, gender: '男', hometown: '河北省'},
            {name: '小红', age: 19, gender: '女', hometown: '河南省'},
            {name: '小刚', age: 17, gender: '男', hometown: '山西省'},
            {name: '小丽', age: 18, gender: '女', hometown: '山东省'}
        ]
        // 渲染页面
        for (let i = 0; i < students.length; i++) {
            document.write(`<tr>`)
            document.write(`<td>${i + 1}</td>`)
            for (let k in students[i]) {
                document.write(`<td>${students[i][k]}</td>`);
            }
            document.write(`</tr>`)
        }
        // 表格结尾
        document.write(`</table>`)
    </script>

2. 猜数字游戏

需求:程序随机生成1 ~ 10 之间的一个数字,用户输入一个数字

 (1). 如果大于该数字,就提示,数字猜大了,继续猜

 (2). 如果小于该数字,就提示,数字猜小了,继续猜

 (3). 如果猜对了,就提示,猜对了,程序结束

        // 随机生成一个数字1 ~ 10
        function getRandom (N, M) {
            return Math.floor(Math.random() * (M - N + 1) + N)
        }
        let random = getRandom(1, 10)
        // 需要不断
        while (true) {
            // 用户输入一个值
            let num = +prompt('请输入你猜的数字')
            // 判断输出
            if (num > random) {
                alert('数字猜大了')
            }else if (num < random) {
                alert('数字猜小了')
            }else if (num === random) {
                alert('猜对了')
                break
            }
        }

设定指定次数的若未猜对时,也退出循环,且弹出次数已经用完。

function getRandom (N, M) {
            return Math.floor(Math.random() * (M - N + 1) + N)
        }
        let random = getRandom(1, 10)
        let flag = true //开关变量
        // 设定三次,三次没猜对就直接退出循环
        for (let i = 1; i <= 3; i++) {
            // 用户输入一个值
            let num = +prompt('请输入你猜的数字')
            // 判断输出
            if (num > random) {
                alert('数字猜大了')
            }else if (num < random) {
                alert('数字猜小了')
            }else if (num === random) {
                flag = false
                alert('猜对了')
                break //退出循环
            }          
        }
        if (flag) {
                alert('次数已经用完了')
        }

3. 生成随机颜色

    // 自定义随机颜色函数
    function getRandomColor(flag = true) {
        if (flag) {
            // 如果为 true 则返回#ffffff
            let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
            let color = '#'
            // 利用 for循环随机抽6次,累加到color里面
            for (let i = 0; i < 6; i++) {
                // 每次要随机从数组里面抽取一个
                let random = Math.floor(Math.random() * arr.length)
                color += arr[random]
            }
            return color
        } else {
            // 否则是false ,则返回rgb(0,0,0)
            let r = Math.floor(Math.random() * 256)
            let g = Math.floor(Math.random() * 256)
            let b = Math.floor(Math.random() * 256)   
            return `rgb(${r}, ${g}, ${b})`
        }
    } 
    // 调用函数 getRandomColor(布尔值)
    console.log(getRandomColor(false))
    console.log(getRandomColor())
    console.log(getRandomColor(true))

 4. 学成在线页面渲染案例

标题标签有自己的padding,margin,故css初始化是非常必要的(* { padding: 0; margin: 0;})

注意在渲染时,图片路径src="images/course01.jpg"改为src=${data[i].src} 不需要加引号,因为data[i].src数据中包含了引号,但图片提示文字title 需要用双引号包起来 title="${data[i].title}",不包的话,只会显示该对象属性中空格前的内容,因为该属性内容可能包含空格

    <link rel="stylesheet" href="./css/style.css">
</head>
<body>
     <!-- 4. box核心内容区域开始 -->
     <div class="box w">
        <div class="box-hd">
            <h3>精品推荐</h3>
            <a href="#">查看全部</a>
        </div>
        <div class="box-bd">
            <ul class="clearfix">
                <!-- <li>
                    <a href="#">
                        <img src="images/course01.jpg" alt="">
                        <h4>
                            Think PHP 5.0 博客系统实战项目演练
                        </h4>
                        <div class="info">
                            <span>高级</span> • <span>1125</span>人在学习
                        </div>
                    </a>
                </li> -->
                <script>
                    // 数据
                    let data = [
                        {
                            src: 'images/course01.jpg',
                            title: 'Think PHP 5.0 博客系统实战项目演练',
                            num: 1125
                        },
                        {
                            src: 'images/course02.jpg',
                            title: 'Android 网络动态图片加载实战',
                            num: 357
                        },
                        {
                            src: 'images/course03.jpg',
                            title: 'Angular2 大前端商城实战项目演练',
                            num: 22250
                        },
                        {
                            src: 'images/course04.jpg',
                            title: 'Android APP 实战项目演练',
                            num: 389
                        },
                        {
                            src: 'images/course05.jpg',
                            title: 'UGUI 源码深度分析案例',
                            num: 124
                        },
                        {
                            src: 'images/course06.jpg',
                            title: 'Kami2首页界面切换效果实战演练',
                            num: 432
                        },
                        {
                            src: 'images/course07.jpg',
                            title: 'UNITY 从入门到精通实战案例',
                            num: 888
                        },
                        {
                            src: 'images/course08.jpg',
                            title: 'Cocos 深度学习你不会错过的实战',
                            num: 590
                        },
                    ]
                    for (let i = 0; i < data.length; i++) {
                        document.write(` 
                        <li>
                            <a href="#">
                                <img src=${data[i].src} alt="" title="${data[i].title}">
                                <h4>
                                    ${data[i].title}
                                </h4>
                                <div class="info">
                                    <span>高级</span> • <span>${data[i].num}</span>人在学习
                                </div>
                            </a>
                        </li>`)
                    }
                </script>  
            </ul>
        </div>
    </div>
</body>

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值