「JavaScript」编程练习题
1、使用if else 语句判断年份为闰年或者是平年
var year = prompt('Please input years:');
if (year % 4 == 0 && year % 100 !== 0 || year % 400 == 0) {
alert('this is a 闰年.');
} else {
alert('this is not a 闰年.');
}
2、if else if 语句实现成绩等级划分
var score = prompt("Please input your score:");
if (score < 0 || score > 100) {
alert('你可真是个熊孩子.');
} else if (score >= 90) {
alert('excellent!');
} else if (score >= 80) {
alert("Good!");
} else if (score >= 70) {
alert('Pass!');
} else {
alert('You are a bad boy!');
}
3、使用三元判断符
var year = prompt('Please input years:');
alert(year > 2000 ? '这是21世纪' : '你来自上世纪');
// 等价于下面的代码:
var year = prompt('Please input years:');
if (year > 2000) {
alert('这是21世纪');
} else {
alert('你来自上世纪');
}
4、使用三元判断符 对秒数进行处理
var sec = prompt('请输入秒数:');
var resultSec = sec < 10 ? '0' + sec : sec;
alert('处理后的秒数为:' + resultSec);
三元运算符甚至可以进行嵌套使用,举个小栗子:当输入数字大于100的时候直接输出,小于10的时候前面补两个0;大于10小于100的时候,前面补两个0。
let sec = prompt('请输入秒数:');
let secByHandle = a < 100 ? (a < 10 ? '00' + a : '0' + a) : a;
console.log(secByHandle)
一个页面倒计时(计时器)小案例:
<!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>
<style>
#countdown-box {
width: fit-content;
margin: 10px auto;
}
#countdown-box>span {
/* 转化span模式,使span能设置宽高 */
display: inline-block;
width: 3em;
height: 3em;
background-color: #333;
color: #fff;
font-weight: 900;
/* 使方块中文字居中 */
text-align: center;
line-height: 3em;
}
#countdown-box strong {
font-size: 150%;
font-weight: 600;
}
</style>
</head>
<body>
<div id="countdown-box">
<span class="day">00</span> <strong>:</strong>
<span class="hour">00</span> <strong>:</strong>
<span class="minute">00</span> <strong>:</strong>
<span class="second">00</span>
</div>
</body>
</html>
<script>
//获取元素
var countdown_box = document.querySelector("#countdown-box");
var day = countdown_box.querySelector(".day");
var hour = countdown_box.querySelector(".hour");
var minute = countdown_box.querySelector(".minute");
var second = countdown_box.querySelector(".second");
//获取截止时间的时间戳(单位毫秒)
var inputTime = +new Date("2022-10-02 16:54:00");
//我们先调用countDown函数,可以避免在打开界面后停一秒后才开始倒计时
countDown();
//定时器 每隔一秒变化一次
setInterval(countDown, 1000);
function countDown() {
//获取当前时间的时间戳(单位毫秒)
var nowTime = +new Date();
//把剩余时间毫秒数转化为秒
var times = (nowTime - inputTime) / 1000;
if (times > 0) {
//计算天 转化为整数
var d = parseInt(times / 60 / 60 / 24);
day.innerHTML = d < 100 ? (d < 10 ? '00' + d : '0' + d) : d;
//计算小时数 转化为整数
var h = parseInt(times / 60 / 60 % 24);
//如果小时数小于 10,要变成 0 + 数字的形式 赋值给盒子
hour.innerHTML = h < 10 ? "0" + h : h;
//计算分钟数 转化为整数
var m = parseInt(times / 60 % 60);
//如果分钟数小于 10,要变成 0 + 数字的形式 赋值给盒子
minute.innerHTML = m < 10 ? "0" + m : m;
//计算描述 转化为整数
var s = parseInt(times % 60);
//如果秒钟数小于 10,要变成 0 + 数字的形式 赋值给盒子
second.innerHTML = s < 10 ? "0" + s : s;
}
}
</script>
5、switch case 语句使用
switch (parseInt(prompt('请输入一个数字:'))) {
case 1:
alert('你输入的是1');
break;
// 如果没有break语句,则会继续执行下一个case语句.
case 2:
alert('你输入的是2');
break;
case 3:
alert('你输入的是3');
break;
default:
alert('非法!!!');
}
6、for循环
var count = prompt('请输入打招呼的次数:');
if (count % 1 !== 0) {
alert('你输个小数是想干嘛?');
} else {
if (count <= 0) {
alert('你输入一个非正整数是想干啥?');
} else {
for (var i = 1; i <= count; i++) {
console.log("这是第" + i + "次输出:你好.")
}
}
}
7、求1~100的和
var result = 0;
for (var i = 1; i <= 100; i++) {
result += i;
}
console.log("1~100的和为:" + result);
8、分别求1~100的所有奇数、偶数和
var sumOven = sumOdd = 0;
for (var i = 1; i <= 100; i++) {
if (i % 2 == 0) {
sumOven += i;
} else {
sumOdd += i;
}
}
console.log('1~100的奇数求和为:' + sumOdd);
console.log('1~100的偶数求和为:' + sumOven);
9、计算班级平均成绩
var count = prompt('请输入班级总人数:');
var sumScore = 0;
for (var i = 1; i <= count; i++) {
var personScore = parseFloat(prompt('请输入第' + i + '个人的成绩:'));
if (personScore < 0 || personScore > 100) {
alert('输入成绩不合法,请重新输入!');
i--;
continue;
}
sumScore += personScore;
}
var averageScore = sumScore / count
console.log('班级内一共有' + count + '个同学的平均成绩为:' + averageScore);
10、双重for循环 大打印正三角形
for (var i = 1; i <= 10; i++) {
var star = '';
for (var j = 1; j <= i; j++) {
star += '★';
}
console.log(star);
}
//双重for循环 大打印倒三角形
for (var i = 10; i >= 1; i--) {
var star = '';
for (var j = 1; j <= i; j++) {
star += "★";
}
console.log(star);
}
10、 JS 打印 9×9乘法表
var str = '';
for (var i = 1; i <= 9; i++) {
for (var j = 1; j <= i; j++) {
if (i * j < 10) {
str += j + '×' + i + '= ' + (i * j) + ' ';
} else {
str += j + '×' + i + '=' + (i * j) + ' ';
}
}
str += '\n';
}
console.log(str);
11、while 循环实现网页密码访问
var password = prompt('请输入访问密码:');
var count = 1;
while (true) {
if (password != '981001') {
if (count >= 3) {
alert("访问失败!");
break;
} else {
alert('输入密码错误!你还有 ' + (3 - count) + ' 次机会!');
count++;
password = prompt('请输入访问密码:');
continue;
}
} else {
alert("访问成功!");
break;
}
}
12、组遍历求和与平均数
var arr = [1, 2, 4, 21, 12, 23];
var average = 0,
result = 0;
for (var i = 0; i < arr.length; i++) {
result += arr[i];
}
console.log('数组求和结果为:' + result + ',平均值为:' + result / arr.length);
13、遍历数组求最值
var arr = [-12, 2, 66, 48, 12, 23];
var maxValue = minValue = arr[0];
for (var i = 1; i < arr.length; i++) {
if (arr[i] > maxValue) {
maxValue = arr[i];
}
if (arr[i] < minValue) {
minValue = arr[i];
}
}
console.log(maxValue);
console.log(minValue);
14、for 循环生成数组
var arr = [];
var arrLength = prompt("请输入数组长度:");
while (arrLength % 1 != 0 || arrLength <= 0) {
alert('输入数组长度不合法!');
arrLength = prompt("请输入数组长度:");
}
for (var i = 0; i < parseInt(arrLength); i++) {
arr[i] = i;
}
console.log(arr);
15、对数组进行筛选
var arr0 = [-12, 2, 66, 48, 12, 23];
var arr1 = [];
var arr2 = [];
var j = k = 0;
for (var i = 0; i < arr0.length; i++) {
if (arr0[i] > 10) {
arr1[j] = arr0[i];
j++;
}
if (arr0[i] < 0) {
arr2[k] = arr0[i];
k++;
}
}
注意,这里的JS数组定义有一个坑!!!如果定义arr1 = arr2
,那么运算完毕后,arr1 = arr2
仍然成立!!!
var arr1 = arr2 = [];
arr1[1] = 1;
arr2[2] = 2;
console.log(arr1);
console.log(arr2);
// 控制台输出
arr1 = [empty, 1 ,2];
arr2 = [empty, 1 ,2];
16、翻转数组
var arr = [-12, 2, 66, 48, 12, 23];
var newArr = [];
for (var i = 0; i < arr.length; i++) {
newArr[arr.length - i - 1] = arr[i];
}
console.log(newArr);
// 方法二
var newArr2 = [];
for (var i = arr.length - 1; i >= 0; i--) {
newArr2[newArr2.length] = arr[i];
}
console.log(newArr2);
17、冒泡排序
var arr = [12, 14, 4, 9, -12, 342, 11, 9];
var temp;
for (var i = 0; i < arr.length - 1; i++) {
for (var j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// console.log('本程序一共进行了i次外循环,j次内循环');
console.log(arr);
18、function
封装for
循环遍历数组求最大值
function getArrayMax(arr) {
var maxValue = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] > maxValue) {
maxValue = arr[i];
}
}
return maxValue;
}
var result = getArrayMax([1, 12, 2, -2, -12, 1, 2]);
console.log(result);
19、function
封装函数实现反转数组
function reverseArray(arr) {
var newArr = [];
for (var i = arr.length - 1; i >= 0; i--) {
newArr[newArr.length] = arr[i];
}
return newArr;
}
console.log(reverseArray([1, 2, 3, 4, 5]));
console.log(reverseArray(['red', 'green', 'cyan', 'blue']));
20、function
封装函数实现冒泡排序
function sort(arr) {
for (var i = 0; i < arr.length - 1; i++) {
for (var j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
var temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
console.log(sort([5, 3, 1, 6, 32, 9, 3, 56]));
21、function函数之间的调用
function isLeapYear(year) {
var mark = false;
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
mark = true;
}
return mark;
}
function printMessage(year) {
if (isLeapYear(year)) {
alert('是闰年!!!');
} else {
alert('不是闰年!!!');
}
}
console.log(printMessage(1999));
22、声明对象的两种方式
var dog = {
name: '可可',
type: '阿拉斯加',
age: 5,
color: 'cyan',
bark: function() {
console.log('汪汪汪...')
},
showFilm: function() {
console.log('我在拍电影...')
}
};
console.log(dog);
console.log(dog.name);
console.log(dog.type);
console.log(dog.age);
dog.bark();
dog.showFilm();
var person = new Object();
person.name = '鸣人';
person.sex = '男';
person.age = 19;
person.skill = '我会分身术哦...';
console.log(person);
23、构造函数创建对象
function CreatStar(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
this.sing = function(sing) {
console.log(sing)
}
}
var ldh = new CreatStar('刘德华', 18, '男');
var lm = new CreatStar('黎明', 19, '男');
console.log(ldh);
console.log(lm);
ldh.sing('冰雨');
24、自定义Math函数API实现
var myMath = {
PI: 3.1415926,
Max: function() {
var maxValue = arguments[0];
for (var i = 1; i < arguments.length; i++) {
if (maxValue < arguments[i]) {
maxValue = arguments[i]
}
}
return maxValue
},
Min: function() {
var minValue = arguments[0];
for (var i = 1; i < arguments.length; i++) {
if (minValue > arguments[i]) {
minValue = arguments[i]
}
}
return minValue
}
}
console.log(myMath.PI);
console.log(myMath.Max(1, 2, 3, 4, 5));
console.log(myMath.Min(1, 2, 3, 4, 5))
25、封装API实现随机点名
function getRandom(minValue, maxValue) {
return Math.floor(Math.random() * (maxValue - minValue + 1)) + minValue
}
function rollCall(nameArray) {
var num = getRandom(0, nameArray.length - 1);
return nameArray[num]
}
var name = rollCall(['红太狼', '灰太狼', '美羊羊', '喜羊羊', '懒洋洋', '沸羊羊', '村长一枝花', '黑大帅']);
console.log(name);
26、利用Math API产生随机数
function getRandom(minValue, maxValue) {
return Math.floor(Math.random() * (maxValue - minValue + 1)) + minValue
}
var randomValue = getRandom(0, 10);
while (true) {
var inputValue = prompt('开始猜猜猜...');
if (inputValue < randomValue) {
alert('你猜小了...')
} else if (inputValue > randomValue) {
alert('你猜大了...')
} else {
alert('恭喜你,猜对了...');
break;
}
}
27、利用 Date() 构造函数生成友好时间
var time = new Date(), //Date() 为构造函数,因此需要新生成一个对象.
year = time.getFullYear(),
month = time.getMonth() + 1, //月份从0开始,因此要加1
dates = time.getDate(),
days = time.getDay(), //星期日为0,星期一为1,星期六为6
week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
console.log('当前时间为' + year + '年' + month + '月' + dates + '日' + week[days]);
28、封装时间函数
function getTime() {
var time = new Date(),
hours = time.getHours(),
minutes = time.getMinutes(),
seconds = time.getSeconds();
hours = hours < 10 ? '0' + hours : hours;
minutes = minutes < 10 ? '0' + minutes : minutes;
seconds = seconds < 10 ? '0' + seconds : seconds;
return hours + ':' + minutes + ':' + seconds
}
console.log(getTime());
29、JavaScript获取Unix时间戳
// 获得Date总的毫秒数(时间戳) 不是当前时间的毫秒数 而是距离1970年1月1号过了多少毫秒数
// 1. 通过 valueOf() getTime()
var date = new Date();
console.log(date.valueOf()); // 就是 我们现在时间 距离1970.1.1 总的毫秒数
console.log(date.getTime());
// 2. 简单的写法 (最常用的写法)
var date1 = +new Date(); // +new Date() 返回的就是总的毫秒数
console.log(date1);
// 3. H5 新增的 获得总的毫秒数
console.log(Date.now());
30、实现倒计时功能
<script>
setInterval(function countDown() {
var oldTime = new Date('2017/07/02 12:00:00'),
nowTime = new Date();
nowTime = nowTime.getTime();
oldTime = oldTime.getTime();
var timeDifference = nowTime - oldTime,
days = parseInt(timeDifference / (24 * 60 * 60 * 1000)),
hours = parseInt(timeDifference / 60 / 60 / 1000 % 24),
minutes = parseInt(timeDifference / 60 / 1000 % 60),
seconds = timeDifference / 1000 % 60;
seconds = seconds.toFixed(3);
hours = hours < 10 ? '0' + hours : hours;
minutes = minutes < 10 ? '0' + minutes : minutes;
seconds = seconds < 10 ? '0' + seconds : seconds;
document.getElementById('countDownDays').innerHTML = days;
document.getElementById('countDownHours').innerHTML = hours;
document.getElementById('countDownMinutes').innerHTML = minutes;
document.getElementById('countDownSeconds').innerHTML = seconds;
}, 10);
</script>
<p>本站已运<span id='countDownDays'>0</span>天<span id='countDownHours'>0</span>小时<span id="countDownMinutes">0</span>分钟<span id="countDownSeconds">0</span>秒...</p>
32、数组去重
function removeDuplicate(arr) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
var index = newArr.indexOf(arr[i]);
if (index === -1) {
newArr.push(arr[i]);
}
}
return newArr;
}
console.log(removeDuplicate(['a', 'b', 'a', 'c', 'c', 'b', 'd', 'e', 'a', 'w']));
33、在字符串中查找字母
function findLetter(str, letter) {
var count = str.indexOf(letter);
var num = 0;
while (count != -1) {
// console.log(count);
// count++;
num++;
count = str.indexOf('a', count + 1);
}
return '您输入的字符串经过查找,共有' + num + '个' + letter + '字符.';
}
console.log(findLetter('asascxsfdfdfaadsqaadssaa', 'a'));