1. -判断是否是闰年
* - 能被400整除,或者能被4整除但不能被100整除的都是闰年,其余的年份均为平年。
被400的为世纪闰年,被4是普通闰年。其余为平年。
// 用户输入一个年份,通过函数来判断输入的年份是闰年还是平年。
<script>
var year = Number(prompt('请输入要判断的年份'));
function leap(year) {
if (year <= 100) {
if (year % 4 == 0) {
return '普通闰年';
} else {
return '平年';
}
} else if (year > 100) {
if (year % 4 == 0 && year % 400 == 0) {
return '世纪闰年';
} else {
return '平年';
}
} else {
year = Number(prompt('请重新输入要判断的年份'));
}
}
var result = leap(year);
console.log(year + '是' + result);
</script>
优化一下:注释的内容是下面内容的扩写,便于理解。以防特殊用户,加入了取整。
<script>
function isLeapYear(year) {
year = parseInt(year);
if (isNaN(year)) {
return '请输入一个正确的年份';
}
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
// if (year % 400 == 0) {
// return '当前年份是世纪闰年';
// }
// return '当前年份是普通闰年';
if (year % 400 == 0) return '当前年份是世纪闰年';
return '当前年份是普通闰年';
}
return '当前年份是平年';
// if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
// return '当前年份是闰年';
// } else {
// return '当前年份是平年';
// }
}
var y = prompt('请输入需要测试的年份:');
console.log(isLeapYear(y));
</script>
2. 函数计算圆的面积和周长
// 定义周长和面积函数,用程序来计算圆的面积和周长。
<script>
var R = Number(prompt('请输入要计算圆的半径(单位m)'));
function calculated_area(R) {
return parseInt(Math.PI * 100) / 100 * (R ** 2);
}
function calculated_perimeter(R) {
return parseInt(Math.PI * 100) / 100 * R * 2;
}
document.write('圆的面积是:' + calculated_area(R) + '平方米<br/>');
document.write('圆的周长是:' + calculated_perimeter(R) + '米<br/>');
</script>
3. 两个整数相互交换
<script>
function num_template(a, b) {
[a, b] = [b, a];
console.log(a)
console.log(b)
}
var a = 1;
var b = 2;
num_template(a, b);
</script>
多个数转置:
<script>
function exchangeNum(...nums) {
nums.reverse();
console.log(nums);
}
exchangeNum(4, 5);//自行输入
</script>
4. 点击为盒子添加边框样式
body里面:
<!-- 点击为盒子添加边框样式 -->
<div class="box" id="box"
style="width:600px;height:300px;background-color:#97f0e4;box-sizing: border-box;border-radius: 3px;"></div>
js代码:
<script>
//-------------------------- 点击为盒子添加边框样式
var box = document.getElementById('box');
box.onclick = function borderStyle() {
box.style.border = '10px solid red';
}
</script>