案例1:计算两个数的和
var num1 = 5;
var num2 = 10;
var sum = num1 + num2;
console.log("两个数的和是:" + sum);
案例2:判断一个数是否是偶数
var num = 7;
if (num % 2 === 0) {
console.log(num + "是偶数");
} else {
console.log(num + "是奇数");
}
案例3:计算数组中所有元素的平均值
var numbers = [1, 2, 3, 4, 5];
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
var average = sum / numbers.length;
console.log("平均值是:" + average);
案例4:找出数组中的最大值
var numbers = [2, 5, 1, 9, 3];
var max = numbers[0];
for (var i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
console.log("数组中的最大值是:" + max);
案例5:反转字符串
var str = "Hello World!";
var reversedStr = "";
for (var i = str.length - 1; i >= 0; i--) {
reversedStr += str[i];
}
console.log("反转后的字符串是:" + reversedStr);
案例6:判断一个字符串是否是回文
var str = "level";
var reversedStr = "";
for (var i = str.length - 1; i >= 0; i--) {
reversedStr += str[i];
}
if (str === reversedStr) {
console.log(str + "是回文");
} else {
console.log(str + "不是回文");
}
案例7:生成指定范围内的随机整数
var min = 1;
var max = 10;
var randomNum = Math.floor(Math.random() * (max - min + 1)) + min;
console.log("随机数是:" + randomNum);
案例8:获取当前日期和时间
var now = new Date();
console.log("当前日期和时间是:" + now);
案例9:将字符串转换为大写
var str = "hello world!";
var upperCaseStr = str.toUpperCase();
console.log("转换为大写后的字符串是:" + upperCaseStr);
案例10:计算阶乘
function factorial(num) {
if (num === 0) {
return 1;
} else {
return num * factorial(num - 1);
}
}
var num = 5;
var result = factorial(num);
console.log(num + "的阶乘是:" + result);