JS常用方法(四)

下面是JavaScript 常用方法和功能的分类汇总,分多篇总结,此为第四篇:数学方法、日期方法。

  • 数学方法

1. Math.random(): 返回一个0到1之间的随机数。

console.log(Math.random()); // 输出 0 到 1 之间的随机数

2. Math.floor(x): 返回小于或等于x的最大整数。

console.log(Math.floor(3.7)); // 输出 3

3. Math.ceil(x): 返回大于或等于x的最小整数。

console.log(Math.ceil(3.1)); // 输出 4

4. Math.round(x): 返回x四舍五入后的值。

console.log(Math.round(3.5)); // 输出 4

5. Math.max(...values): 返回一组数中的最大值。

console.log(Math.max(1, 2, 3)); // 输出 3

6. Math.min(...values): 返回一组数中的最小值。

console.log(Math.min(1, 2, 3)); // 输出 1

7. Math.abs(x): 返回x的绝对值。

console.log(Math.abs(-5)); // 输出 5

8. Math.sqrt(x): 返回x的平方根。

console.log(Math.sqrt(16)); // 输出 4

9. Math.pow(base, exponent): 返回base的exponent次方。

console.log(Math.pow(2, 3)); // 输出 8
  • 日期方法

1. Date.now(): 返回当前时间的时间戳(毫秒)。

console.log(Date.now()); // 输出当前时间的时间戳

2. new Date(): 创建一个新的日期对象。

const date = new Date();
console.log(date); // 输出当前日期和时间

3. Date.parse(dateString): 解析一个日期字符串并返回时间戳。

console.log(Date.parse("2023-10-01")); // 输出对应的时间戳

4. Date.prototype.getFullYear(): 返回日期对象的年份。

const date = new Date();
console.log(date.getFullYear()); // 输出当前年份

5. Date.prototype.getMonth(): 返回日期对象的月份(0-11)。

const date = new Date();
console.log(date.getMonth()); // 输出当前月份 (0-11)

6. Date.prototype.getDate(): 返回日期对象的天(1-31)。

const date = new Date();
console.log(date.getDate()); // 输出当前日期 (1-31)

7. Date.prototype.getDay(): 返回日期对象的星期几(0-6)。

const date = new Date();
console.log(date.getDay()); // 输出当前星期几 (0-6)

8. Date.prototype.getHours(): 返回日期对象的小时(0-23)。

const date = new Date();
console.log(date.getHours()); // 输出当前小时 (0-23)

9. Date.prototype.getMinutes(): 返回日期对象的分钟(0-59)。

const date = new Date();
console.log(date.getMinutes()); // 输出当前分钟 (0-59)

10. Date.prototype.getSeconds(): 返回日期对象的秒(0-59)。

const date = new Date();
console.log(date.getSeconds()); // 输出当前秒 (0-59)

11. Date.prototype.setFullYear(year): 设置年份。

const date = new Date();
date.setFullYear(2025);
console.log(date.getFullYear()); // 输出 2025

12. Date.prototype.setMonth(month): 设置月份。

const date = new Date();
date.setMonth(0); // 设置为1月
console.log(date.getMonth()); // 输出 0

13. Date.prototype.setDate(date): 设置日期。

const date = new Date();
date.setDate(15);
console.log(date.getDate()); // 输出 15

猜你喜欢

转载自blog.csdn.net/qq_46094169/article/details/142094178