前端三剑客实验5-6-复盘

实验 5 - JavaScript对象

若需要源代码,文章末尾自提

1、实现如下编程内容:

1. 分别使用工厂模式、构造函数和class模式来构建移动硬盘对象

在这里插入图片描述

2. 彩票号码生成器

随机生成7个1-36之间的随机数,要求数字不重复,并按从小到大的顺序排序输出到控制台。

3. 在一些电商网站的活动页上会经常出现折扣商品的倒计时标记,显示离活动结束还剩X天X小时X分X秒。编制一个函数,把促销截止的目标时间作为参数传入,然后在控制器台每间隔1s显示促销结束倒计时。

4. 要求在一组字符串中,找到并在控制台输出所有指定元素出现的位置以及次数。字符串为“Hello World, Hello JavaScript”。

2、具体代码实现

第一题

<!DOCTYPE html>
<html lang="zh-CN">
<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>PortableHD 对象</title>
  <script>
    // 工厂模式
    function createPortableHDByFactory(brand, capacity, price) {
      return {
        brand: brand,
        capacity: capacity,
        price: price,
        showInfo: function () {
          return `品牌:${this.brand},容量:${this.capacity}GB,价格:$${this.price}`;
        },
        readData: function () {
          // 实际读取数据的逻辑
          return '读取数据中...';
        },
        writeData: function () {
          // 实际写入数据的逻辑
          return '写入数据中...';
        }
      };
    }

    // 构造函数
    function PortableHDByConstructor(brand, capacity, price) {
      this.brand = brand;
      this.capacity = capacity;
      this.price = price;
      this.showInfo = function () {
        return `品牌:${this.brand},容量:${this.capacity}GB,价格:$${this.price}`;
      };
      this.readData = function () {
        return '读取数据中...';
      };
      this.writeData = function () {
        return '写入数据中...';
      };
    }

    // Class 模式
    class PortableHDByClass {
      constructor(brand, capacity, price) {
        this.brand = brand;
        this.capacity = capacity;
        this.price = price;
      }

      showInfo() {
        return `品牌:${this.brand},容量:${this.capacity}GB,价格:$${this.price}`;
      }

      readData() {
        return '读取数据中...';
      }

      writeData() {
        return '写入数据中...';
      }
    }

    // 验证工厂模式
    const portableHDFactory = createPortableHDByFactory('品牌A', 500, 100);
    console.log(portableHDFactory.showInfo());
    console.log(portableHDFactory.readData());
    console.log(portableHDFactory.writeData());

    // 验证构造函数
    const portableHDConstructor = new PortableHDByConstructor('品牌B', 1000, 150);
    console.log(portableHDConstructor.showInfo());
    console.log(portableHDConstructor.readData());
    console.log(portableHDConstructor.writeData());

    // 验证 Class 模式
    const portableHDClass = new PortableHDByClass('品牌C', 2000, 200);
    console.log(portableHDClass.showInfo());
    console.log(portableHDClass.readData());
    console.log(portableHDClass.writeData());
  </script>
</head>
<body>
  <h1>PortableHD 对象</h1>
  <p>在控制台中查看对象信息和方法调用。</p>
</body>
</html>

运行结果
在这里插入图片描述

2、第二题

<!DOCTYPE html>
<html lang="zh-CN">
<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>彩票号码生成器</title>
  <script>
    function generateLotteryNumbers() {
      const lotteryNumbers = [];

      // 生成7个不重复的随机数
      while (lotteryNumbers.length < 7) {
        const randomNum = Math.floor(Math.random() * 36) + 1;
        if (!lotteryNumbers.includes(randomNum)) {
          lotteryNumbers.push(randomNum);
        }
      }

      // 按从小到大的顺序排序
      lotteryNumbers.sort((a, b) => a - b);

      // 输出到控制台
      console.log('生成的彩票号码:', lotteryNumbers);

      // 将结果显示在页面上
      const resultContainer = document.getElementById('result');
      resultContainer.textContent = '生成的彩票号码: ' + lotteryNumbers.join(', ');
    }

    // 在页面加载时生成彩票号码
    window.onload = generateLotteryNumbers;
  </script>
</head>
<body>
  <h1>彩票号码生成器</h1>
  <p id="result">生成中...</p>
</body>
</html>

运行结果
在这里插入图片描述

3、第三题

<!DOCTYPE html>
<html lang="zh-CN">
<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>促销倒计时</title>
  <script>
    function startCountdown(targetTime) {
      const targetDate = new Date(targetTime).getTime();

      // 更新倒计时每秒钟
      const countdownInterval = setInterval(function() {
        const now = new Date().getTime();
        const timeRemaining = targetDate - now;

        if (timeRemaining <= 0) {
          clearInterval(countdownInterval);
          console.log('促销已结束');
        } else {
          const days = Math.floor(timeRemaining / (1000 * 60 * 60 * 24));
          const hours = Math.floor((timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
          const minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
          const seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);

          console.log(`距离促销结束还剩 ${days}${hours}小时 ${minutes}分钟 ${seconds}`);
        }
      }, 1000);
    }

    // 在页面加载时启动倒计时,目标时间为当前时间的5分钟后
    window.onload = function() {
      const targetTime = new Date().getTime() + 5 * 60 * 1000; // 5分钟后
      startCountdown(targetTime);
    };
  </script>
</head>
<body>
  <h1>促销倒计时</h1>
  <p>在控制台查看倒计时。</p>
</body>
</html>

运行结果
请添加图片描述

4、第四题

<!DOCTYPE html>
<html lang="zh-CN">
<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>查找元素位置和次数</title>
  <script>
    function findElementOccurrences(inputString, targetElement) {
      const positions = [];
      let index = inputString.indexOf(targetElement);

      while (index !== -1) {
        positions.push(index);
        index = inputString.indexOf(targetElement, index + 1);
      }

      const count = positions.length;

      if (count > 0) {
        console.log(`元素 "${targetElement}" 在字符串中出现的位置:${positions}`);
        console.log(`元素 "${targetElement}" 在字符串中出现的次数:${count}`);
      } else {
        console.log(`元素 "${targetElement}" 未在字符串中找到`);
      }
    }

    // 在页面加载时调用示例
    window.onload = function() {
      const inputString = "Hello World, Hello JavaScript";
      const targetElement = "Hello";
      findElementOccurrences(inputString, targetElement);
    };
  </script>
</head>
<body>
  <h1>查找元素位置和次数</h1>
  <p>在控制台查看输出结果。</p>
</body>
</html>

运行结果
在这里插入图片描述

实验6 Javascript DOM -1操作实验

资料见文末

1、实验内容和过程:

实现如下编程内容:

1. 自行设定表单界面,求某范围的质数。

操作要求如下:
 数字的开始范围和结束范围自行在文本输入框录入,然后点击“查询”按钮后,
在下方网页中显示这个范围内对应的质数。
 质数输出为红色数字,每行输出10个
 最后统计质数的数量和所有质数数字之和

2. 编制案例,在一个屏幕居中的文本框中输入密码信息,要求如下:

 所有密码信息用号表示
 点击右侧“眼睛”图片后,可以去除
号字符遮蔽,显示为明文数字。

2、具体实现

1、第一题具体实现:

<!DOCTYPE html>
<html lang="zh-CN">
<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>质数查询</title>
  <style>
    .prime {
      color: red;
      margin-right: 10px;
    }
  </style>
  <script>
    function isPrime(number) {
      if (number < 2) return false;
      for (let i = 2; i <= Math.sqrt(number); i++) {
        if (number % i === 0) {
          return false;
        }
      }
      return true;
    }

    function findPrimes() {
      const startRange = parseInt(document.getElementById('startRange').value);
      const endRange = parseInt(document.getElementById('endRange').value);

      if (isNaN(startRange) || isNaN(endRange) || startRange >= endRange) {
        alert('请输入有效的数字范围!');
        return;
      }

      const primesContainer = document.getElementById('primesContainer');
      primesContainer.innerHTML = ''; // 清空之前的结果

      let primeCount = 0;
      let primeSum = 0;

      for (let number = startRange; number <= endRange; number++) {
        if (isPrime(number)) {
          primeCount++;
          primeSum += number;

          const primeElement = document.createElement('span');
          primeElement.textContent = number;
          primeElement.className = 'prime';

          primesContainer.appendChild(primeElement);

          if (primeCount % 10 === 0) {
            primesContainer.appendChild(document.createElement('br'));
          }
        }
      }

      const resultSummary = `质数数量: ${primeCount}, 质数总和: ${primeSum}`;
      document.getElementById('resultSummary').textContent = resultSummary;
    }
  </script>
</head>
<body>
  <h1>质数查询</h1>
  <form>
    <label for="startRange">开始范围:</label>
    <input type="number" id="startRange" required>
    <label for="endRange">结束范围:</label>
    <input type="number" id="endRange" required>
    <button type="button" onclick="findPrimes()">查询</button>
  </form>
  <div id="primesContainer"></div>
  <p id="resultSummary"></p>
</body>
</html>

运行结果
请添加图片描述

2、第二题具体实现 (需要images文件夹)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>密码款的小眼睛</title>
    <style>
      .box {
        position: relative;
        width: 400px;
        border: 1px solid #ccc;
        margin: 100px auto;
        padding: 2px;
      }
      .box input {
        width: 370px;
        height: 30px;
        border: 0;
        outline: none;
      }
      .box img {
        position: absolute;
        top: 4px;
        right: 6px;
        width: 24px;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <label for="">
        <img src="images/close.png" alt="" id="eye">
      </label>
      <input type="password" name="" id="pwd">
    </div>

    <script>
      // 1. 获取元素
      var eye = document.getElementById('eye');
      var pwd = document.getElementById('pwd');

      // 2. 注册事件处理程序
      var flag = 0;
      eye.onclick = function () {
        // 每次单击,修改flag的值
        if (flag == 0) {
          pwd.type = 'text';
          eye.src = 'images/open.png';
          flag = 1;
        } else {
          pwd.type = 'password';
          eye.src = 'images/close.png';
          flag = 0;
        }
      };
      
    </script>

  </body>
</html>

运行结果
在这里插入图片描述

3、资料自提(若过期,请留言)

实验5:

链接:https://pan.baidu.com/s/1azl5_wwM-M_1l-Vh3c8Lzg?pwd=mwps
提取码:mwps

实验6:

链接:https://pan.baidu.com/s/1YWdCnRxXLxAR-Z9xzRKgXw?pwd=5dr4
提取码:5dr4

  • 20
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值