JS经典练习题

持续更新中…

一. 利用case穿透简化代码

  • 输入月份,显示当月的总天数

    var month = 2;
    var year = 2000;
    
    switch (month) {
      case 1:
      case 3:
      case 5:
      case 7:
      case 8:
      case 10:
      case 12:
        console.log(31);
        break;
      case 2:
        if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
          console.log(29);
        } else {
          console.log(28);
        }
        break;
      default:
        console.log(30)
        break
    }
    

二. 利用数组求平均数

// 定义一个含有30个偶数的数组,按顺序分别赋予从2开始的偶数
// 然后按顺序每五个数求出一个平均值,放在另一个数组中并输出。试编程
// 1.声明数组
var arr = new Array(30);
for (var i = 0; i < arr.length; i++) {
  arr[i] = i * 2 + 2;
}
// console.log(arr);

// 2.求平均数
var averageArr = [];
for (var i = 0; i < 6; i++) {
  // 3.取出求平均数的这组数
  // var newArr = arr.splice(0, 5);
  var newArr = arr.slice(i * 5, (i + 1) * 5);
  console.log(newArr);
  // 4.求平均数
  var sum = 0;
  for (var j = 0; j < newArr.length; j++) {
    sum += newArr[j];
  }
  averageArr.push(sum / 5);
}
console.log(averageArr);

三. 计算数组中每个元素出现的次数

let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice', 'Alice'];
let nameNum = names.reduce((pre, cur) => {
  cur in pre ? pre[cur]++ : pre[cur] = 1
  return pre
}, {})
console.log(nameNum); //{Alice: 3, Bob: 1, Tiff: 1, Bruce: 1}

四. 数组去重

let arr = [1, 2, 3, 4, 4, 1]
let newArr = arr.reduce((pre, cur) => {
  if (!pre.includes(cur)) {
    return pre.concat(cur)
  } else {
    return pre
  }
}, [])
console.log(newArr);// [1, 2, 3, 4]

五. 将二维数组转化为一维

let arr = [[0, 1], [2, 3], [4, 5]]
let newArr = arr.reduce((pre, cur) => {
  return pre.concat(cur)
}, [])
console.log(newArr); // [0, 1, 2, 3, 4, 5]

六. 将多维数组转化为一维

let arr = [[0, 1], [2, 3], [4, [5, 6, 7]]]
const newArr = function (arr) {
  return arr.reduce((pre, cur) => pre.concat(Array.isArray(cur) ? newArr(cur) : cur), [])
}
console.log(newArr(arr)); //[0, 1, 2, 3, 4, 5, 6, 7]

七. 生成随机的字符串验证码

// 传入需要生成验证码的个数

// 生成纯数字验证码
function numTestCode(n) {
  var arr = [];
  for (var i = 0; i < n; i++) {
    var num = parseInt(Math.random() * 10);
    arr.push(num);
  }
  return arr.join("");
}
console.log(numTestCode(6));

// 生成带有数字、字母的随机验证码
// 分析:
//       0~9
//       a~z   ASCII码值 97~122
//       A~Z   ASCII码值 65~90
//       遍历0~122
//       使用Math.random()生成,需要得到字母的ASCII码值,然后再转为字母(fromCharCode())
function testCode(n) {
  var arr = [];
  for (var i = 0; i < n; i++) {
    var num = parseInt(Math.random() * 123);
    if (num >= 0 && num <= 9) {
      arr.push(num);
    } else if (num >= 97 && num <= 122 || num >= 65 && num <= 90) {
      arr.push(String.fromCharCode(num));
    } else {
      i--;
    }
  }
  return arr.join("")
}
console.log(testCode(6));

八. 字体大小颜色随机变化

<style>
  #box {
    width: 500px;
    height: 400px;
    margin: 100px auto;
    border: 1px solid #000;
    font-size: 30px;
    font-weight: 700;
    text-align: center;
    line-height: 400px;
  }
</style>

<script>
  // 写一个定时器,每隔一秒修改一次div内文本颜色和文字大小
  // 最开始这个文字是默认大小,大小开始增大,当增大了6次以后
  // 文字大小开始缩小,缩小6次,文字再开始增大,依次循环
  function randomColor() {
    // 借鉴一
    var colorStr = `rgba(${parseInt(Math.random() * 256)}, ${parseInt(Math.random() * 256)}, ${parseInt(Math.random() * 256)}, 1)`
    return colorStr
  }
  // console.log(randomColor());
  window.onload = function() {
    var oDiv = document.getElementById("box")
    var fontSizeSpeed = 10
    var count = 0

    setInterval(() => {
      oDiv.style.color = randomColor()
      // 借鉴二
      var divFontSize = parseInt(getComputedStyle(oDiv)["font-size"])
      oDiv.style.fontSize = divFontSize + fontSizeSpeed + "px"
      count++
      // 借鉴三
      if (count % 6 === 0) {
        fontSizeSpeed *= -1
      }
    }, 300);
  }
</script>

<div id="box">厚德载物</div>

九. 跟随鼠标移动的提示框

<style>
  a {
    display: block;
    font-size: 40px;
    margin: 100px;
    width: 130px
  }

  #msg {
    width: 600px;
    height: 150px;
    background-color: gray;
    color: white;
    display: none;
    position: absolute;
  }
</style>

<script>
  /* 
    事件类型:
      mouseover
          让提示框显示
      mouseout
          让提示框隐藏
      mousemove
          让提示框跟随鼠标去移动
            clientX  clientY  原点位置:可视窗口的左上角为原点
   */
  var arr = ["唐太宗李世民(598年1月28日-649年7月10日),陇西成纪(今甘肃省秦安县)人。唐朝第二位皇帝(626~649年在位),杰出的政治家、战略家、军事家、诗人,唐高祖李渊嫡次子,母为太穆皇后窦氏", "唐高宗李治(628年7月21日-683年12月27日) [1]  ,字为善,祖籍陇西成纪,唐朝第三位皇帝(649至683年在位),唐太宗李世民第九子,嫡三子,其母为文德顺圣皇后长孙氏,与唐太宗嫡长子太子李承乾、嫡次子魏王李泰为同母兄弟。", "武则天(624年-705年12月16日 [1]  ),自名武曌(zhào) [2-3]  ,并州文水(今山西文水)人。中国历史上唯一的正统女皇帝(690年-705年在位),也是即位年龄最大(67岁)、寿命最长的皇帝之一(82岁),与汉朝的吕后并称为“吕武”。", "唐玄宗李隆基(685年9月8日—762年5月3日),唐高宗李治与武则天之孙,唐睿宗李旦第三子,故又称李三郎,母窦德妃。 [1]  先天元年(712年)至天宝十五年(756年)在位,因安史之乱退位为太上皇,是唐朝在位最长的皇帝,亦是唐朝极盛时期的皇帝。"];
  //【注】arr数组中是按照a标签的下标去存储对应的描述信息的
  window.onload = function () {
    var aAs = document.getElementsByTagName("a");
    var oMsg = document.getElementById("msg");

    for (var i = 0; i < aAs.length; i++) {
      aAs[i].index = i;
      aAs[i].onmouseover = function () {
        oMsg.innerHTML = arr[this.index];
        oMsg.style.display = 'block';
      }

      aAs[i].onmouseout = function () {
        oMsg.style.display = 'none';
      }

      //添加鼠标移动事件
      aAs[i].onmousemove = function (ev) {
        var e = ev || window.event;
        oMsg.style.left = e.clientX + 15 + 'px';
        oMsg.style.top = e.clientY + 10 + 'px';
      }
    }
  }
</script>

<a href="#">唐太宗</a>
<a href="#">唐高宗</a>
<a href="#">武则天</a>
<a href="#">唐玄宗</a>
<div id = 'msg'></div>

十. 鼠标移动的效果

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

  div {
    position: absolute;
    width: 20px;
    height: 20px;
    background-color: red;
    border-radius: 50%
  }
</style>
<script>
  window.onload = function () {
    var arr = document.getElementsByTagName("div");
    document.onmousemove = function (ev) {
      var e = ev || window.event;
      // 1、让最后一个div跟着上一个div移动
      for (var i = arr.length - 1; i > 0; i--) {
        arr[i].style.left = arr[i - 1].offsetLeft + 'px';
        arr[i].style.top = arr[i - 1].offsetTop + 'px';
      }

      // 2、然后让第一个div跟随鼠标移动
      arr[0].style.left = e.clientX + 'px';
      arr[0].style.top = e.clientY + 'px';
    }
  }
</script>

<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</body>

十一. 拖拽

function limitDrag(node) {
	node.onmousedown = function (ev) {
		var e = ev || window.event;
		// 记录鼠标和被拖拽物体相对位置
    // e.clientX:可视窗口最左边缘到点击位置的距离
    // node.offsetLeft:子绝父相中的父级最左边缘到子div最左边缘之间的距离
		var offsetX = e.clientX - node.offsetLeft;
		var offsetY = e.clientY - node.offsetTop;

		//被拖拽物体保持相对距离和鼠标移动
		document.onmousemove = function (ev) {
			var e = ev || window.event;
      // 得到子绝父相中的子父相对距离
			var l = e.clientX - offsetX;
			var t = e.clientY - offsetY;

			//限制出界
			if (l <= 0) {
				l = 0;
			}
			var windowWidth = document.documentElement.clientWidth || document.body.clientWidth;
			if (l >= windowWidth - node.offsetWidth) {
				l = windowWidth - node.offsetWidth;
			}

			if (t <= 0) {
				t = 0;
			}
			var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
			if (t >= windowHeight - node.offsetHeight) {
				t = windowHeight - node.offsetHeight;
			}

			node.style.left = l + 'px';
			node.style.top = t + 'px';
		}
	}
	//取消拖拽
	document.onmouseup = function () {
		document.onmousemove = null;
	}
}

// 使用
var oDiv1 = document.getElementById("div1");
limitDrag(oDiv1);

十二. 图片放大镜

<style>
  #small {
    width: 300px;
    height: 560px;
    position: absolute;
    left: 100px;
    top: 100px
  }

  #small img {
    width: 100%;
    height: 100%
  }

  #mark {
    display: none;
    width: 200px;
    height: 200px;
    background-color: white;
    opacity: 0.5;
    filter: alpha(opacity=50);
    position: absolute;
    left: 0px;
    top: 0px
  }

  #big {
    display: none;
    width: 400px;
    height: 400px;
    border: 1px solid black;
    left: 500px;
    top: 100px;
    position: absolute;
    overflow: hidden;
  }

  #big img {
    width: 600px;
    height: 1120px;
    position: absolute;
    left: 0px;
    top: 0px
  }
</style>

<script>
  window.onload = function () {
    var oSmall = document.getElementById("small");
    var oBig = document.getElementById("big");
    var oMark = document.getElementById("mark");
    var oBigImg = oBig.getElementsByTagName("img")[0];

    oSmall.onmouseover = function () {
      oMark.style.display = 'block';
      oBig.style.display = 'block';
    }
    oSmall.onmouseout = function () {
      oMark.style.display = 'none';
      oBig.style.display = "none";
    }

    oSmall.onmousemove = function (ev) {
      var e = ev || window.event;
      var l = e.clientX - oSmall.offsetLeft - 100;
      var t = e.clientY - oSmall.offsetTop - 100;
      if (l <= 0) {
        l = 0;
      }
      if (l >= 100) {
        l = 100;
      }
      if (t <= 0) {
        t = 0;
      }
      if (t >= 360) {
        t = 360;
      }
      oMark.style.left = l + 'px';
      oMark.style.top = t + 'px';

      /* 
          右边图片的移动方式,左边遮罩层如何移动,右边图片,反方向对应倍数移动
      */
      oBigImg.style.left = l * -2 + 'px';
      oBigImg.style.top = t * -2 + 'px';
    }
  }
</script>

<div id='small'>
  <img src="timg.jpeg" alt="" />
  <div id='mark'></div>
</div>
<div id='big'>
  <img src="timg.jpeg" alt="" />
</div>

十三. 表单验证和密码强度验证

偷个懒,直接放链接:表单验证和密码强度验证

十四. 滑动条

<style>
  #slide {
    position: relative;
    width: 600px;
    height: 30px;
    border: 1px solid black;
    margin: 100px auto
  }

  #block {
    width: 30px;
    height: 30px;
    background-color: blue;
    position: absolute;
    left: 0px
  }

  #full {
    width: 0px;
    height: 30px;
    background-color: orange;
    position: absolute;
    top: 0px;
    left: 0px
  }
</style>

<script>
  window.onload = function () {
    var oSlide = document.getElementById("slide");
    var oFull = document.getElementById("full");
    var oBlock = document.getElementById("block");

    //重新获取是否存储滑动的位置
    if (!window.localStorage) {
      alert("该浏览器,不支持localStorage");
    } else {
      //取出本地存储中的值
      var l = localStorage.getItem("slide") ? localStorage.getItem("slide") : 0;
      oBlock.style.left = l + 'px';
      //填充部分要跟随滑块,进行填充
      oFull.style.width = l + 'px';
    }

    oBlock.onmousedown = function (ev) {
      var e = ev || window.event;
      // e.clientX:可视窗口最左边缘到点击位置的距离
      // oBlock.offsetLeft:子绝父相中的父级最左边缘到子div最左边缘之间的距离
      var offsetX = e.clientX - oBlock.offsetLeft;

      document.onmousemove = function (ev) {
        var e = ev || window.event;
        // 得到子绝父相中的子父相对距离
        var l = e.clientX - offsetX;
        if (l <= 0) {
          l = 0;
        }
        if (l >= 570) {
          l = 570;
        }

        oBlock.style.left = l + 'px';
        //填充部分要跟随滑块,进行填充
        oFull.style.width = l + 'px';
        //对当前滑块的位置,进行本地存储
        if (!window.localStorage) {
          alert("该浏览器,不支持localStorage");
        } else {
          localStorage.setItem("slide", l);
        }
      }
    }
    // 取消拖拽
    // 鼠标松开回收document.onmousemove函数
    document.onmouseup = function () {
      document.onmousemove = null;
    }
  }
</script>

<body>
  <div id='slide'>
    <div id='full'></div>
    <div id='block'></div>
  </div>
</body>

十五. 使用集合实现单词搜索

<style>
  #div1 {
    width: 200px;
    height: 200px;
    padding: 50px;
    background-color: lightgray;
    border: 1px solid black;
    margin: 100px auto
  }

  #word {
    width: 200px;
    height: 30px;
    font-size: 18px;
  }

  #desc {
    width: 200px;
    height: 150px;
    margin-top: 20px;
    padding: 10px;
    background-color: lightgreen;
    box-sizing: border-box;
  }
</style>
<!-- <script src='demo.js'></script> -->
<script>
  // 要严格按照这里的格式来,如果格式变了,下面字符串分割也要相应的变化
  var word = 
    `#a
    Trans:art. 一;字母A
    #a.m.
    Trans:n. 上午
    #a/c
    Trans:n. 往来帐户@往来:come - and - go; contact; intercourse@n. 往来帐户
    #aardvark
    Trans:n. 土猪
    #aardwolf
    Trans:n. 土狼
    #aasvogel
    Trans:n. 秃鹰之一种
    #abaci
    Trans:n. 算盘`

  //1、将字符串通过换行进行字符串分割
  var arr = word.split(/\n\s{0,10}/);
  let map = new Map();
  for (var i = 0; i < arr.length - 1; i += 2) {
  	// 将word里面的数据按照key(单词)和value(汉语翻译)的形式存到map中
    map.set(arr[i].substring(1), arr[i + 1].substring(6));
  }
  window.onload = function () {
    var oWord = document.getElementById("word");
    var oDesc = document.getElementById("desc");
    oWord.onkeyup = function () {
      var value = map.get(this.value);
      if (value) {
        oDesc.innerHTML = value.split("@").join("<br/>");
      } else {
        oDesc.innerHTML = "查无此词";
      }
    }
  }
</script>

<div id="div1">
  <input id='word' type="text" placeholder="输入英文单词" />
  <div id='desc'></div>
</div>
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值