一、条件类
判断三个数的大小,并从小到大排列
var num1 = +prompt("请输入数字:");
var num2 = +prompt("请输入数字:");
var num3 = +prompt("请输入数字:");
if(num1 > num2 && num1 > num3){
if(num2 > num3){
alert(num3 + "," + num2 + "," + num1);
}else{
alert(num2 + "," + num3 + "," + num1);
}
}else if(num2 > num1 && num2 > num3){
if(num1 > num3){
alert(num3 + "," + num1 + "," + num2);
}else{
alert(num1 + "," + num3 + "," + num2);
}
}else{
if(num1 > num2){
alert(num2 + "," + num1 + "," + num3);
}else{
alert(num1 + "," + num2 + "," + num3);
}
}
判断学生成绩是否合格
var score = prompt("请输入分数:");
switch(parseInt(score / 10)){
case 10:
case 9:
case 8:
case 7:
case 6:
console.log("及格啦");
break;
default:
console.log("不及格");
}
输入日期,判断这个日期是这一年的第几天
var date = prompt("请输入8位数日期:");
var year = parseInt(date / 10000)
var month = parseInt(date / 100) % 100;
var day = date % 100;
var count = 0;
var february = 28;
switch(month - 1){
case 12:
count += 31;
case 11:
count += 30;
case 10:
count += 31;
case 9:
count += 30;
case 8:
count += 31;
case 7:
count += 31;
case 6:
count += 30;
case 5:
count += 31;
case 4:
count += 30;
case 3:
count += 31;
case 2:
if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0){
count += 29;
}else{
count += 28;
}
case 1:
count += 31;
break
}
count += day;
alert("第" + count + "天");
二、循环类
打印1000-2000之间的闰年,每行打印4个
for(var i = 1000 , count = 0 ; i < 2001 ; i++){
if(i % 4 === 0 && i % 100 !== 0 || i % 400 === 0){
document.write(i + " ");
count++;
}
// count为计数器
if(count % 4 === 0){
document.write("<br>")
}
}
打印水仙花数
for(var i = 100 ; i < 1000 ; i++){
var a = i % 10; // 个位数字
var b = parseInt(i / 10) % 10; // 十位数字
var c = parseInt(i / 100); // 百位数字
// i === Math.pow(a, 3) + Math.pow(b, 3) + Math.pow(c, 3)
// i === a ** 3 + b ** 3 + c ** 3
if(i === a * a * a + b * b * b + c * c * c){
document.write(i + "<br>");
}
}
打印1-100之间所有的质数
for(var i = 2 ; i < 101 ; i++){
var flag = true; //使用中间量 flag 记录状态
for(var j = 2 ; j < i ; j++){ //代码优化1: j < i 改为 j <= Math.sqrt(i)
if(i % j === 0){
flag = false;
break; //代码优化2
}
}
if(flag){
console.log(i);
}
}
判断某个数是否是质数
var num = prompt("请输入一个大于1的数字:");
var flag = true; //使用中间量 flag 记录状态
for(var i = 2 ; i < num ; i++){
if(num % i === 0){
flag = false;
break;
}
}
if(flag){
document.write(num + "是质数");
}else{
document.write(num + "不是质数");
}
打印三角形
for(var i = 0 ; i < 10 ; i++){
for(var j = 0 ; j < i + 1 ; j++){
document.write("* ");
}
document.write("<br>");
}
打印倒三角形
for(var i = 10 ; i > 0 ; i--){
for(var j = 0 ; j < i ; j++){
document.write("* ");
}
document.write("<br>")
}
打印等腰三角形
for(var i = 0 ; i < 10 ; i++){
for(var j = 0 ; j < i * 2 + 1 ; j++){
document.write("* ");
}
document.write("<br>")
}
打印菱形
for(var i = 0 ; i < 10 ; i++){
for(var j = 0 ; j < i * 2 + 1 ; j++){
document.write("* ");
}
document.write("<br>")
}
for(var i = 8 ; i >= 0 ; i--){
for(var j = 0 ; j < i * 2 + 1 ; j++){
document.write("* ");
}
document.write("<br>")
}
打印空心菱形
for(var i = 0 ; i < 10 ; i++){
for(var j = 0 ; j < i * 2 + 1 ; j++){
if(j === 0 || j === i * 2){
document.write("* ");
}else{
document.write(" ");
}
}
document.write("<br>")
}
for(var i = 8 ; i >= 0 ; i--){
for(var j = 0 ; j < i * 2 + 1 ; j++){
if(j === 0 || j === i * 2){
document.write("* ");
}else{
document.write(" ");
}
}
document.write("<br>")
}
打印99乘法表
for(var i = 1 ; i < 10 ; i++){
for(var j = 1 ; j < i + 1 ; j++){
document.write(j + "*" + i + "=" + j * i + " ");
}
document.write("<br>");
}
三、函数类
编写函数,计算三个数字的大小,按从小到大的顺序打印
function fun(a, b, c) {
var temp;
if(a > b){
temp = a;
a = b;
b = temp;
}
if(a > c){
temp = a;
a = c;
c = temp;
}
if(b > c){
temp = b;
b = c;
c = temp;
}
console.log("从小到大的顺序是" + a + "," + b + "," + c);
}
fun(11, -2, 5);
编写函数,在页面上打印一个N行M列的表格,表格内容填充0~100的随机数字
function printForm(N, M){
document.write("<table>")
for(i = 0 ; i < N ; i++){
document.write("<tr>")
for(j = 0 ; j < M ; j++){
document.write("<td>" + parseInt(Math.random() * 101) + "</td>")
}
document.write("</tr>")
}
document.write("</table>")
}
printForm(8, 5);
编写函数,实现功能:foo(1)(2)(3)(4) 打印 24
function foo(a){
return function(b){
return function(c){
return function(d){
console.log(a * b * c * d);
}
}
}
}
foo(1)(2)(3)(4);
编写函数,实现点击按钮随便改变页面和按钮背景颜色
<body id="body">
<button id="btn">变换背景颜色</button>
function setRandomColor(ele, color){
var r = color === "red" ? 255 : parseInt(100 * Math.random());
var g = color === "green" ? 255 : parseInt(100 * Math.random());
var b = color === "blue" ? 255 : parseInt(100 * Math.random());
random_color = "rgb(" + r + "," + g + "," + b + ")";
ele.style.cssText = "background-color : " + random_color;
}
btn.onclick = function(){
setRandomColor(body, "red");
setRandomColor(btn, "green");
}
编写函数,实现随机点名
<button id="btn">随机点名</button>
function getRandomName(){
var random_index = parseInt(arguments.length * Math.random());
return arguments[random_index];
}
btn.onclick = function(){
var random_name = getRandomName("吴京", "吴奇隆", "吴彦祖", "吴亦凡", "吴孟达", "吴晨");
console.log(random_name);
}
编写函数,计算两个数字的和差积商
function calculate(a, b, operator){
switch(operator){
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
case "/":
return a / b;
}
}
console.log(calculate(10, 2, "/"));
编写函数,判断一个字符串的内容是不是纯数字,返回true或false
function fun(a){
return Number(a) || a === "0" ? true : false;
}
编写函数,生成4位数字的验证码
function generateCode(){
var code = "";
for(var i = 0; i < 4; i++){
code += parseInt(Math.random() * 10)
}
return code;
}
console.log(generateCode());
某个公司采用公用电话传递数据,数据是四位的整数,在传递过程中是加密的,加密规则如下:每位数字都加上5,然后用除以10的余数代替该数字,再将第一位和第四位交换,第二位和第三位交换,请编写一个函数,传入原文,输出密文
function generatePassword(i){
// 千位数字
var a = (parseInt(i / 1000) + 5) % 10;
// 百位数字
var b = (parseInt(i / 100) % 10 + 5) % 10;
// 十位数字
var c = (parseInt(i / 10) % 10 + 5) % 10;
// 个位数字
var d = (i % 10 + 5) % 10;
var temp = a;
a = d;
d = temp;
temp = b;
b = c;
c = temp;
return a * 1000 + b * 100 + c * 10 + d;
}
console.log(generatePassword(3759));
编写函数,计算任意两个数字之间所能组成的奇数个数,数字必须是个位数。比如:计算0~3之间能组成的奇数是: 01、03、13、21、23、31
function countOdd(a, b){
// 默认a<b,若a>b则a,b换位
if(a > b){
var temp = a;
a = b;
b = temp;
}
for(var i = a , count = 0 ; i <= b ; i++){
for(var j = a ; j <= b ; j++){
if(i % 2 !== 0 && j !== i){
console.log("" + j + i);
count++;
}
}
}
return count;
}
console.log(countOdd(3, 0));
四、递归类
编写函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数求1/1+1/3+...+1/n
function calculator(n){
if(n === 1 || n === 2){
return 1 / n;
}
return 1 / n + calculator(n - 2);
}
console.log(calculator(5));
console.log(calculator(6));
在页面输入任意数字,点击按钮后计算该数字的阶乘
function factorial(n){
if(n === 1){
return 1;
}
return n * factorial(n - 1);
}
var value = prompt("请输入数字:");
btn.onclick = function(){
console.log(factorial(value));
}
斐波那契数列(1,1,2,3,5,8···)
function fun(i){
if(i === 1 || i === 2){
return 1;
}
return fun(i - 1) + fun(i - 2);
}
console.log(fun(3));
辗转相除法(求最大公约数)
function fun(a, b){
if(a % b === 0){
return b;
}
var r = a % b;
a = b;
b = r;
return fun(a , b);
}
console.log(fun(16, 24));
五、数组类
定义一个含有30个整型元素的数组,按顺序分别赋予从2开始的偶数;然后按顺序每五个数求出一个平均值,放在另一个数组中并输出。试编程
var arr = [];
var res = [];
var sum = 0;
for(var i = 1 ; i < 31 ; i++){
arr.push(2 * i);
sum += 2 * i;
if(i % 5 === 0){
res.push(sum / 5);
sum = 0;
}
}
console.log(res);
编写函数map(arr) 把数组中的每一位数字都增加30%,并返回一个新数组
function map(arr){
var new_arr = [];
for(var i = 0; i < arr.length; i++){
// Math.round 解决数组元素中存在浮点数时的计算误差问题
new_arr.push(Math.round(arr[i] * 1.3 * 10) / 10);
}
return new_arr;
}
var arr = [1, 10, 100, 1000, 10000];
console.log(map(arr));
有一个从小到大排好序的数组。现输入一个数,要求按原来的规律将它插入数组中
function sort(arr, value){
if(arr[arr.length - 1] <= value){
arr.push(value);
}else{
for(var i = 0 ; i < arr.length ; i++){
if(arr[i] > value){
arr.splice(i, 0, value);
break;
}
}
}
return arr;
}
var arr = [1, 5, 8, 10, 14];
var value = +prompt("请输入数字:");
console.log(sort(arr, value));
编写函数norepeat(arr) 将数组的重复元素去掉,并返回新的数组
function norepeat(arr){
for(var i = 0; i < arr.length; i++){
for(var j = i + 1; j < arr.length; j++){
if(arr[i] === arr[j]){
arr.splice(j, 1);
j--;
}
}
}
return arr;
}
var arr = [1, 2, 2, 5, 5, 6, 4, 4, 7, 1, 3, 5];
console.log(norepeat(arr));
通过循环按执行顺序,做一个5×5的二维数组,赋1到25的自然数,然后输出该数组的左下半三角。试编程
var arr =[];
var res = [];
var new_arr = [];
for(var i = 1; i < 26; i++){
res.push(i);
if(i % 5 === 0){
arr.push(res);
res = [];
}
}
for(var j = 0; j < 5 ; j++){
new_arr.push(arr[j].slice(0, j + 1));
}
console.log(arr);
console.log(new_arr);
实现filter、every、some函数
function filter(arr, fn){
var res_arr = [];
for(var i = 0; i < arr.length; i++){
var res = fn(arr[i]);
if(res){
res_arr.push(arr[i]);
}
}
return res_arr;
}
function every(arr, fn){
var flag = true;
for(var i = 0; i < arr.length; i++){
if(!fn(arr[i])){
flag = false;
break;
}
}
return flag;
}
function some(arr, fn){
var flag = false;
for(var i = 0; i < arr.length; i++){
if(fn(arr[i])){
flag = true;
break;
}
}
return flag;
}
var arr = [1, 2, 3, 4, 5];
console.log(filter(arr, function(item){
return item > 3;
}))
console.log(every(arr, function(item){
return item > 3;
}))
console.log(some(arr, function(item){
return item > 3;
}))
六、字符串类
编写函数,输出四位数的数字字母混合验证码(数字+大写字母+小写字母)
function getRandomInt(min , max){
return min + parseInt( Math.random() * (max - min + 1));
}
function generateCode(){
var min, max;
var code = "";
for(var i = 0 ; i < 4 ; i ++){
switch(getRandomInt(1 , 3)){
case 1 :
min = 48;
max = 57;
break;
case 2 :
min = 65;
max = 90;
break;
case 3 :
min = 97;
max = 122;
break;
}
var randomInt = getRandomInt(min , max);
code += String.fromCharCode(randomInt);
}
return code;
}
console.log(generateCode());
aabccd统计每个字符出现的次数,使结果显示为一个对象,如:{a:2, b:1, c:2, d:1},去掉重复的字符,使结果显示 abcd
function fn(str){
var obj = {};
for(var i = 0; i < str.length; i++){
var attr = str[i];
if(obj[attr] === undefined){
obj[attr] = 1;
}else{
obj[attr]++;
}
}
console.log(obj);
var string = "";
for(var key in obj){
string += key;
}
console.log(string);
}
var str = "aabccd";
fn(str);
编写函数,判断一个字符串是否是 “可回文字符串”,如:abccba。是:true;不是:false
// 方法1
function judgePalindrome(str){
var n = parseInt((str.length + 1) / 2);
var flag = true;
for(var i = 0; i < n; i++){
if(str[i] !== str[str.length - i - 1]){
flag = false
break;
}
}
return flag;
}
// 方法2
function judgePalindrome(str){
// 字符串 => 数组 => 倒序数组 => 字符串
var new_str = str.split("").reverse().join("");
return str === new_str;
}
console.log(judgePalindrome("abccba"));
console.log(judgePalindrome("abcgcba"));
console.log(judgePalindrome("abcdba"));
编写函数,获得一个十六进制的随机颜色的字符串(例如:#20cd4f)
function getColorNum(){
var color = "#";
for(var i = 0 ; i < 6 ; i ++){
color += parseInt(Math.random() * 15).toString(16);
}
return color;
}
console.log(getColorNum());
字符串拼接配合json实现商品列表布局
<head>
<style>
body{margin: 0; padding: 0; background: #b6b6b6; }
.center{ width: 1380px; height: 233px; margin: 0 auto; }
.center .box{ width: 260px; height: 193px; border-radius: 4px; float: left; margin-right: 20px; background: #fff; }
.center .box:last-of-type{ margin-right: 0; }
.center .box img{ width: 260px; height: 146px; }
.center .box p{ padding: 0 10px; margin-top: 4px; font: 14px/1.5 "PingFang SC","Lantinghei SC","Microsoft YaHei","HanHei SC","Helvetica Neue","Open Sans",Arial,"Hiragino Sans GB","微软雅黑",STHeiti,"WenQuanYi Micro Hei",SimSun,sans-serif; }
</style>
</head>
<body>
<div class="center" id="center"></div>
<script>
var json = `[
{
src : "https://image.gogoup.com/course/20181016/1539669673749.jpg",
title : "教你画卡通IP"
},
{
src : "https://image.gogoup.com/course/20190115/1547541116847.jpg",
title : "商业插画之时尚人物篇"
},
{
src : "https://image.gogoup.com/course/20180824/1535089522410.jpg",
title : "10堂课看懂西方艺术史"
},
{
src : "https://image.gogoup.com/course/20200301/1583074941120.png",
title : "UI设计适配与落地"
},
{
src : "https://image.gogoup.com/course/20181016/1539689983190.jpg",
title : "商业UI设计:全链式设计方法与流程"
}
]`
var item_list = eval(json);
var insert_html = "";
for(var i = 0; i < item_list.length; i++){
insert_html += '<div class="box">' +
'<img src="' + item_list[i].src +'" alt="">' +
'<p>' + item_list[i].title +'</p>' +
'</div>'
}
var center = document.getElementById("center");
center.innerHTML = insert_html;
</script>
</body>
</html>
七、Date类
编写函数,把当前时间格式化成 YYYY-MM-DD HH-MM-SS
function getTime(){
var d = new Date();
var res = "";
res += d.getFullYear() + "-";
res += getDblTime(d.getMonth() + 1) + "-";
res += getDblTime(d.getDate()) + " ";
res += getDblTime(d.getHours()) + "-";
res += getDblTime(d.getMinutes()) + "-";
res += getDblTime(d.getSeconds());
return res;
}
function getDblTime(num){
if(num >= 10){ return num; }
return "0" + num;
}
console.log(getTime());
编写函数,要求传入两个日期时间,返回两个日期时间之间,相差 多少天多少小时多少分钟多少秒
function dateReduce(options){
if(options.start === undefined || options.start === "now"){
start_d = new Date();
}else{
var start_str = formateDateArray(options.start);
var start_d = new Date(start_str);
}
var end_str = formateDateArray(options.end);
var end_d = new Date(end_str);
var reduce_ms = end_d.getTime() - start_d.getTime();
return {
days : parseInt(reduce_ms / 1000 / 3600 / 24),
hours : parseInt(reduce_ms / 1000 / 3600 % 24),
min : parseInt(reduce_ms / 1000 / 60 % 60),
sec : parseInt(reduce_ms / 1000 % 60 )
}
}
function formateDateArray( arr ){
var date_str = "";
switch(arr.length){
case 3 :
date_str = arr.join("/");
break;
case 6 :
date_str = arr.slice(0,3).join("/");
date_str += " " + arr.slice(3).join(":")
break;
}
return date_str;
}
var res = dateReduce({
// start : [1995,8,24,8,0,0],
start : "now",
end : [2020,3,6,0,0,0]
});
console.log(res);
编写函数,实现倒计时(5小时)
<p>
倒计时 :
<span id="hour"></span>小时
<span id="min"></span>分钟
<span id="sec"></span>秒
</p>
<script>
var d = new Date();
d.setHours(d.getHours() + 5);
var hour_ele = document.getElementById("hour");
var min_ele = document.getElementById("min");
var sec_ele = document.getElementById("sec");
// 获取时间戳进行计算并返回结果
function countDown(){
var reduce_ms = d.getTime() - Date.now();
return {
hour : parseInt(reduce_ms / 1000 / 3600),
min : parseInt(reduce_ms / 1000 / 60 % 60 ),
sec : Math.round(reduce_ms / 1000 % 60)
}
}
// 向页面渲染数据
function renderCountDown(){
var res = countDown();
hour_ele.innerHTML = addZero(res.hour);
min_ele.innerHTML = addZero(res.min);
sec_ele.innerHTML = addZero(res.sec);
}
// 数值小于10时在前面加0
function addZero( num ){
if(num < 10){
return "0" + num;
}
return num;
}
// 倒计时
setInterval(function(){
renderCountDown();
},1000);
renderCountDown()
</script>
八、事件类
点击按钮回到顶部
<button id="back_to_top">回到顶部</button>
<script>
var back_ele = document.getElementById("back_to_top");
// 方法1,传入x、y轴值
// back_ele.onclick = function(){
// scrollTo(0, 0);
// }
// 方法2,传入对象(平滑效果有兼容问题)
back_ele.onclick = function(){
scrollTo({
top : 0,
behavior : "smooth"
});
}
</script>
导航栏吸顶效果
<div class="nav" id="nav"></div>
<div class="nav-backup" id="nav_backup"></div>
<script>
var height = 300;
var nav_status = "normal";
window.onscroll = function(){
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
var nav_ele = document.getElementById("nav");
var nav_backup_ele = document.getElementById("nav_backup");
if(scrollTop >= height && nav_status === "normal"){
nav_status = "fixed";
nav_ele.style.cssText = "position:fixed; top:0; width:100%;";
nav_backup_ele.style.cssText = "display:block";
}
if(scrollTop < height && nav_status === "fixed"){
nav_status = "normal";
nav.style.cssText = "";
nav_backup_ele.style.cssText = "display:none";
}
}
</script>
动态创建表格,具有删除功能
<table id="table">
<thead>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>ID</th>
<th>操作</th>
</thead>
<tbody id="tbody"></tbody>
</table>
<script>
var obj = { table_list : [ {name : "小明", age : 16, sex : "男", id : 1},
{name : "小红", age : 11, sex : "男", id : 2},
{name : "小丽", age : 16, sex : "男", id : 3} ]}
function createTable(obj){
var arr = obj.table_list;
var tbody_ele = document.getElementById("tbody");
var insert_html = "";
for(var i = 0; i < arr.length; i++){
insert_html += '<tr>' +
'<td>' + arr[i].name + '</td>' +
'<td>' + arr[i].age + '</td>' +
'<td>' + arr[i].sex + '</td>' +
'<td>' + arr[i].id + '</td>' +
'<td><button id=' + i + '>删除</button></td>' +
'</tr>';
}
tbody_ele.innerHTML = insert_html;
var btn = document.getElementsByTagName("button");
for(var j = 0; j < btn.length; j++){
btn[j].onclick = function(){
var index = this.getAttribute("id");
obj.table_list.splice(index, 1);
createTable(obj);
}
}
}
createTable(obj);
</script>