js小案例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
 <style>
    #box{
      width: 100px;
      height: 100px;
      border: 1px solid #000;
    }
  </style>
  <body>
    <!-- 第五题 -->
    <div id="box"></div>
    <button id="btn1">换色</button></br></br></br>

    <!-- 第十题 -->
    <h1>点击下方按钮进入倒计时</h1>
    <button id="btn2">倒计时</button></br></br></br>

    <!-- 第十一题 -->
    <h2>1</h2>
    <button id="btn3">开始</button></br></br></br>
    <!-- 总分:____ -->
    <input type="text" name="" id="ip" />
    <p id="pInfo">info</p>
    <button id="btn">按钮</button>
    <div id="box"></div>

    <script>
      // @流程控制
      // 01 输出100以内全部同时能被3整除的数,最后统计一下数量 +=10
        function fn01(j){
            var arr = []
            for(let i =1; i<100;i++) {
                if(i%j ==0){
                    console.log(i);
                    arr.push(i)
                }
            }
            console.log("100以内全部能被"+j+"整除的数量有"+arr.length+"个");
        }
      // 要被哪个整除就传哪个
      fn01(3)

      // 02 将任意对象(如{name:"jack",age:20,gender:"男",clazz:"2204"}),将其键值以二维数组形式重构 + 0
      // 使结果为[["name":"jack"],["age",20],["gender","男"],["clazz","2204"]]
      // 不许硬编码,必须确保无论给入任何对象,都能正确输出
  
        function fn02() {
           let obj = {
            name:"jack",
            age:20,
            gender:"男"
        }
        let arr = []
        for(var i in obj) {
            let arr1 = []
            // console.log(i,",",obj[i]);
            arr1.push(i,obj[i])
            arr.push(arr1)
        }

        console.log(arr);
      }
      fn02()

      // 03 循环打印1000以内的随机数,直到得到一个完全平方数(1,4,9,16,25...) +10
      function fn03() {
        while (true) {
          const r = parseInt(Math.random() * 100);
          console.log(r);

          if (Math.sqrt(r) % 1 === 0) {
            break;
          }
        }
      }
      // fn03()

      // @函数封装
      // 04 封装一个函数使之并返回入参a,b之间的随机数,要求使用箭头函数(b不一定大于a)
      let getRandom = (a, b) => {
        if (b <= a) {
          let temp;
          temp = a;
          a = b;
          b = temp;
        }
        return a + Math.round((b - a) * Math.random());
      };
      function fn04() {
        console.log(getRandom(1, 10));
        console.log(getRandom(10, 1));
      }
      // fn04()

 

  

     let = fn04 = (a,b) => {
        let min = a
        let max = b
        if(a>b){
          min = b
          max = a
        }
        return parseInt(Math.random() * (b-a) + a)
      }
   //   console.log("随机数",fn04(10,50));
 
      // 05 封装一个能返回随机颜色的函数,如rgb(123,45,67),点击按钮时调用该函数给按钮的文字设置随机颜色
      function fn05() {
        function getRandomColor() {
          return `rgb(${getRandom(0, 255)},${getRandom(0, 255)},${getRandom(
            0,
            255
          )})`;
        }

        btn.onclick = function (e) {
          let c = getRandomColor();
          console.log(c);
          this.style.color = c;
        };
      }
      // fn05()

 

  

     function fn05(b) {
        var num1 = parseInt(Math.random() * 256)
        var num2 = parseInt(Math.random() * 256)
        var num3 = parseInt(Math.random() * 256)
        var res = 'rgb('+num1 + ',' + num2 + ','+ num3 +')'
        // console.log(res);
        b.style.backgroundColor = res
      }
      btn1.onclick = function (){
        fn05(box)
      }
 
      // 06 判断一个数是否为水仙花数(一个三位数,满足各位的立方和相加恰好等于该数本身,例如:153=1^3 + 5^3 + 3^3)
     function fn06(num) {
        var num = parseInt(num);
        // 限定三位数
        if(num >= 100 && num <= 999){
            var b = parseInt(num/100);
            var s = parseInt(num/10)%10;
            var g = parseInt(num%10);
            if(num == b*b*b + s*s*s + g*g*g){
                console.log('水仙花')

            }else{
                console.log('不是水仙花')
            }

        }else{
            console.log('请输入正确的三位数');
        }
      }
      fn06(153)

      // 07 输出九九乘法表
 
      function fn07() {
         for (var i = 1; i <= 9; i++) {
            for (var j = 1; j <= i; j++) {
                document.write(j + "*" + i + "=" + j * i + "&nbsp;&nbsp;");
            }
            document.write("<br>");
        }
      }
      fn07()

      // @系统API(数组、字符串、时间日期、正则)
      // 08 生成50个学生的随机成绩,结构如下:然后映射形成一个带有等级ABC的新数组(必须使用map)
      // 映射前:[{name:"学生1",score:88},{name:"学生2",score:53},...]
      // 映射后:[{name:"学生1",score:88,level:"B"},{name:"学生2",score:53,level:"C"},...]
      function fn08() {
        let arr = [];
        for (var i = 1; i <= 10; i++) {
          arr.push({
            name: `学生${i}`,
            score: Math.round(Math.random() * 100),
          });
        }

        arr = arr.map((item) => ({
          name: item.name,
          score: item.score,
          level: item.score >= 90 ? "A" : item.score >= 60 ? "B" : "C",
        }));
        console.log(arr);
      }
      // fn08()

      // 09 将下列字符串中的脏字替换为等字符数的星号*,使用正则实现
      // "你妹啊!姐尼玛三个月没来大姨妈了!真是坑死你爹我啦!姐特么现在感觉十分的fucking special!"
      
      function fn09() {
        let str  =  "你妹啊!姐尼玛三个月没来大姨妈了!真是坑死你爹我啦!姐特么现在感觉十分的fucking special!"
        let reg = /你妹|尼玛|坑死|特么|fucking|special/g
        console.log(str.replace(reg,(zh)=>zh.replace(/./g ,"*")));
      }
      // fn09()

      // @定时器
      // 10 由用户输入需要倒计时的秒数,点击按钮时显示一个倒计时,结束时显示“boom!!!”并停止计时
      function fn10() {
        btn.onclick = function () {
          let seconds = ip.value * 1;

          // setTimeout(() => {
          //   pInfo.innerText = "BOOM!!!"
          // }, seconds*1000);
          pInfo.innerText = seconds;
          let timer = setInterval(() => {
            pInfo.innerText = --seconds;
            if (seconds === 0) {
              clearInterval(timer);
              pInfo.innerText = "BOOM!!!";
            }
          }, 1000);
        };
      }
      // fn10()

 

 

      var txt = prompt("请输出要倒数的秒数")
      var h1 = document.querySelector('h1');
      var dsq
      function fn10(){
          txt--
          if(txt<0){
              clearInterval(dsq)
              h1.innerText = "boom!!!"
              return
          }
          h1.innerHTML=txt
      }
      btn2.onclick=function(){
          clearInterval(dsq)
          dsq=setInterval(fn10,1000)
      }
 
      // 11 每秒产生并打印递增的自然数1、2、3...,直到100为止,点击【暂停/继续】按钮时实现暂停和继续的切换(注意只有一个按钮)
      function fn11() {
        let count = 0;
        let timer = null;

        btn.onclick = function (e) {
          if (!timer) {
            timer = setInterval(() => {
              console.log(++count);
              if (count >= 10) {
                clearInterval(timer);
              }
            }, 1000);
          } else {
            clearInterval(timer);
            timer = null;
          }
        };
      }
      // fn11()

 

 

      var h2 = document.querySelector('h2');
      var dsq
      function fn11() {
          var txt = h2.innerHTML
          txt++
          if(txt>100){
              clearInterval(dsq)
              return
          }
          h2.innerHTML = txt
      }
      var a = 0
      btn3.onclick=function(){
          if(a == 0){
              a = 1
              btn3.innerHTML = "暂停"
          }else{
              a = 0
              btn3.innerHTML = "开始"
          }
          if(a==1){
              clearInterval(dsq)
              dsq=setInterval(fn11,1000)
          }else{
            clearInterval(dsq)
          }
      }
 
 
      // @DOM与事件
      // 12 创建年与日时分秒皆随机的Date对象,按格式输出:yyyy年MM月dd日 上午/下午 HH:mm:ss(12小时制)
      function getLengthedNumStr(num, len) {
        let str = "";
        for (var i = 0; i < len - (num + "").length; i++) {
          str += "0";
        }
        str += num;
        return str;
      }

      function fn12() {
        const date = new Date(
          parseInt(Math.random() * 2023),
          parseInt(Math.random() * 13),
          parseInt(Math.random() * 32),
          parseInt(Math.random() * 24),
          parseInt(Math.random() * 60),
          parseInt(Math.random() * 60)
        );
        console.log(date);

        console.log(
          `${getLengthedNumStr(date.getFullYear(), 4)}年${getLengthedNumStr(
            date.getMonth() + 1,
            2
          )}月${getLengthedNumStr(date.getDate(), 2)}日 ${
            date.getHours() > 11 ? "下午" : "上午"
          } ${getLengthedNumStr(date.getHours() % 12, 2)}:${getLengthedNumStr(
            date.getMinutes(),
            2
          )}:${getLengthedNumStr(date.getSeconds(), 2)}`
        );
      }
      fn12();

      // 13 当鼠标在div的边框中移动时实时显示光标相对于div的位置,移出时停止显示
      function fn13() {
        box.onmousemove = function (e) {
          pInfo.innerText = `(${e.offsetX},${e.offsetY})`;
        };
      }
      // fn13();

      // 14 手写深拷贝:deepCopy(obj)返回一个obj的深拷贝副本(必须使用递归)
      // {name:"jack",age:20,gender:"男",clazz:"2106",wife:{name:"rose",age:20,gender:"女",clazz:"2204"}}
      function fn14() {}

  

    function fn14(data) {
      let copy
      if (typeof (data) === 'function' || typeof (data) !== 'object') {
        return data
      } else if (Array.isArray(data)) {
        copy = []
        data.forEach(function (item, index) {
          copy[index] = fn14(item)
        })
        return copy
      } else {
        copy = {}
        for (let key in data) {
          copy[key] = fn14(data[key])
        }
        return copy
      }
    }

 

 

      // @面向对象
      // 15 继承链如下:
      // Animal{属性:[legs],方法:[eat]}
      //     ->Person{属性:[name],方法:[think]}
      //         ->Student{属性:[zhuanye],方法:[study]}
      // 造一个学生实例并输出,令其吃饭、思考、学习
      // 使用构造函数+原型而非class进行实现
      // 学生的思考方法需在父类实现基础上进行一定扩展
      function fn15() {
        function Animal(type, legs, food) {
          this.type = type;
          this.legs = legs;
          this.food = food;
        }
        Animal.prototype.eat = function () {
          console.log(`${this.legs}条腿的${this.type}正在浪费${this.food}`);
        };
        Animal.prototype.goDie = function () {
          console.log(`${this.type}眼一闭腿一蹬回去报道了`);
        };

        function Person(name, age) {
          Animal.call(this, "人", 2, "大米饭");
          this.name = name;
          this.age = age;
        }
        Person.prototype = new Animal();
        Person.prototype.think = function () {
          console.log(`${this.name}正在使用它的大脑而不是大腿思考`);
        };

        function Student(name, age, major) {
          Person.call(this, name, age);
          this.major = major;
        }
        Student.prototype = new Person("孙猴子的妈", 500);
        Student.prototype.study = function () {
          console.log(`${this.name}默默打开了Bilibili学习${this.major}`);
        };

        Student.prototype.think = function () {
          Person.prototype.think.call(this);
          console.log("学生think的新扩展");
        };

        const s = new Student("张三丰", 60, "打架");
        s.eat();
        s.think();
        s.study();
      }
      // fn15();

      // 16 随机匹配你的阅卷导师
      // 生成座位号id数组[11...19,21...29,...121...128]
      // 第1~12排的学生人数依次为[8,9,9,9,9,  6,8,8,8,8,  7,8]
      // 生成随机两两匹配结果,例如:[[11,23],[12,45],[13,88]...]
      // 如果学生数量是奇数,则最后一组形如[64,null]
      function fn16() {
        const ids = [];
        const cols = [null, 8, 9, 9, 9, 9, 6, 8, 8, 8, 8, 7, 8];

        for (var i = 1; i <= 3; i++) {
          for (var j = 1; j <= cols[i]; j++) {
            ids.push(i * 10 + j);
          }
        }
        console.log(ids);

        const cps = []
        while(ids.length >= 2){

          let [a] = ids.splice(parseInt(Math.random()*ids.length),1)
          let [b] = ids.splice(parseInt(Math.random()*ids.length),1)

          console.log("a/b",a,b);
          cps.push([a,b])
        }

        if(ids.length){
          cps.push( [ids[0],"臭皮"] )
        }

        console.log(cps);
      }
      fn16();
    </script>
  </body>
</html>
posted @ 2022-07-18 19:30  禅心佛子  阅读(146)  评论(0)    收藏  举报