JavaScript基础——内置对象(Math对象和Date对象)

2021/7/7 17:11:22

本文主要是介绍JavaScript基础——内置对象(Math对象和Date对象),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

内置对象

  • JavaScript中的对象有三种:自定义对象、 内置对象、浏览器对象
  • ECMAScript中的对象:自定义对象、内置对象
  • 内置对象:Math、Array、Date、... ...

学习方法:

  • 最常用的属性和方法
  • 查文档:MDN

Math对象

Math不是一个构造函数,里面提供的是静态成员

属性

Math.PI

Math.PI表示一个圆的周长与直径的比例,约为 3.14159

console.log(Math.PI); // 3.141592653589793

// 计算圆的面积
function getCircleArea(radius) {
	return 2 * Math.PI * radius;
}

var radius = 2;
console.log(getCircleArea(radius)); // 12.566370614359172

方法

Math.ceil()

Math.ceil()函数返回大于或等于一个给定数字的最小整数。

console.log(Math.ceil(0.95)); // 1
console.log(Math.ceil(4)); // 4
console.log(Math.ceil(7.005)); // 8
console.log(Math.ceil(-7.005)) // -7

Math.floor()

Math.floor()返回小于或等于一个给定数字的最大整数

console.log(Math.floor(45.95)); // 45
console.log(Math.floor(45.05)); // 45
console.log(Math.floor(4)); // 4
console.log(Math.floor(-45.05)); // -46
console.log(Math.floor(-45.95)); // -46

Math.max()

Math.max()函数返回一组数中最大值

console.log(Math.max(1, 5, 8, 7, 6, 8, 5)); // 8

Math.min()

Math.max()函数返回一组数中最小值

console.log(Math.max(1, 5, 8, 7, 6, 8, 5)); // 1

Math.pow()

Math.pow()函数返回基数(base)的指数(exponent)次幂。

// 语法
Math.pow(base, exponent)  // base基数 exponent指数

// 案例
console.log(Math.pow(2, 2)) // 4

Math.random()

Math.random()函数返回一个从0到1的随机浮点数,包括0,不包括1

function getRandom() {
    return Math.random();
}

var num1 = getRandom(); // 随机浮点数

Math.round()

Math.round()函数返回一个数字四舍五入后最接近的整数。

console.log(Math.round(20.49)); // 20
console.log(Math.round(20.5)); // 21
console.log(Math.round(-20.49)); // -20
console.log(Math.round(-20.5)); // -20
console.log(Math.round(-20.51)); // -21

注意:

与很多其他语言中的round()函数不同,Math.round()并不总是舍入到远离0的方向(尤其是在负数的小数部分恰好等于0.5的情况下)。

案例

  1. 求10-20之间的随机整数. [10, 20]
function getRandom(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1) + min);
}

console.log(getRandom(10, 20));
  1. 随机生成RGB颜色
function getRGBValue() {
var RValue = Math.floor(Math.random() * (255 + 1));
var GValue = Math.floor(Math.random() * (255 + 1));
var BValue = Math.floor(Math.random() * (255 + 1));
var RGBValue = "RGB" + "(" + RValue + "," +  GValue + "," +  BValue + ")";

return RGBValue;
}
console.log(getRGBValue());
  1. 模拟实现Math.max()/Math.min()
var MyMath = {
max: function () {
var max = arguments[0];
for (var i = 1; i < arguments.length; i++) {
if (max < arguments[i]) {
max = arguments[i];
}
}
return max;
},
min: function () {
var min= arguments[0];
for (var i = 1; i < arguments.length; i++) {
if (min > arguments[i]) {
min = arguments[i];
}
}
return min; 
}
}

console.log(MyMath.max(1,5,2,5,45,24,8,4)); // 45
console.log(MyMath.min(1,5,2,5,45,24,8,4)); // 1

Date对象

MDN文档链接:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date

Date是一个构造函数,首先要通过 new Date() 来创建日期示例(对象),实例成员

var d = new Date()
// 直接打印 d 是一个 GMT 格林威治时间 世界标准时间   GMT+0800(中国标准时间)
console.log(d);  // Wed Jul 07 2021 11:25:01 GMT+0800 (中国标准时间)
// 打印 d 的 valueOf() 是距离1970-1-1相差的毫秒数,如果在1970年以前,打印的是负数值
console.log(d.valueOf()); // 1625628301304
  • 格林威治时间一般指世界时间
  • 北京时差:现在格林威治时间比北京时间晚8小时

Date构造函数的四种用法

// 空构造函数,获取的是当前时间对象
new Date();
// 构造函数中传入毫秒值
new Date(value);
// 构造函数中传入日期形式的字符串(不建议使用)
new Date(dateString);
// 构造函数中传入日期与时间的每一个成员(至少提供年和月两个成员) , 月份是从0开始
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);

获取日期对象的毫秒值

从1970年1月1日0时0分0秒(UTC,即协调世界时)到该日期对象所代表时间的毫秒数。

// 1. valueOf()方法,该方法通常在 JavaScript 内部被调用,一般不用在代码中显式调用
var d = new Date();
console.log(d.valueOf());

// 2. getTime()方法,这个方法的功能和 valueOf() 方法一样
var d = new Date();
console.log(d.getTime());

// 3. Date.now(),Date的静态成员
var d = Date.now();
console.log(d);

// 4. 使用运算符“+”取正的方法获取对象毫秒值
var d = + new Date();
console.log(d);

Date对象的常用方法

隐式调用方法

var d = new Date();
// 1. toString(),转换成字符串
congsole.log(d.toString())

// 2. valueOf(),获取毫秒值
congsole.log(d.valueOf())

日期格式化方法

下面格式化日期的方法,在不同浏览器可能表现不一致,一般不用

var d = new Date();
// 1. toDateString(),转换成美式英语日期部分字符串
congsole.log(d.toDateString())

// 2. toLocaleDateString(),转换成本地日期部分字符串
congsole.log(d.toLocaleDateString())

// 3. toLocaleTimeString(), 转换成本地时间部分字符串
congsole.log(d.toLocaleTimeString())

获取日期指定部分

var d = new Date();
// 1. getTime(),返回毫秒数,和valueOf()结果一样
congsole.log(d.getTime())

// 2. getMilliseconds(),返回毫秒数
congsole.log(d.getMilliseconds())

// 3. getseconds(), 返回秒数,0-59
congsole.log(d.getseconds())

// 4. getMinutes(), 返回分钟数,0-59
congsole.log(d.getMinutes())

// 5. getHours(), 返回小时数,0-23
congsole.log(d.getHours())

// 6. getDay(),返回星期,0代表周日,6代表周六

// 7. getDate(), 返回天数,1-31
congsole.log(d.getDate())

// 8. getMonth(), 返回月数,0-11,0代表1月份,11代表12月份
congsole.log(d.getMonth())

// 9. getFullYear(), 返回4位数年份
congsole.log(d.getFullYear())

格式化日期案例

function formatDate(date) {
	if (!(date instanceof Date)) {
		console.error("date不是日期对象")
		return;
	}


	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var day = date.getDate();
	var hours = date.getHours();
	var minutes = date.getMinutes();
	var seconds = date.getSeconds();

	month = month > 10 ? month : "0" + month;
	day = day > 10 ? day : "0" + day;
	hours = hours > 10 ? hours : "0" + hours;
	minutes = minutes > 10 ? minutes : "0" + minutes;
	seconds = seconds > 10 ? seconds : "0" + seconds;

	return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
}

var d = new Date();
var currentTime = formatDate(d);
console.log(currentTime);

计算日期差

案例:计算时间差,返回相差的天/时/分/秒

function fn(start, end) {
	var interval = d2 - d1;
	interval /= 1000;
	var day = Math.round(interval / 60 / 60 / 24);
	var hours = Math.round(interval / 60 / 60 % 24);
	var minutes = Math.round(interval / 60 % 60);
	var seconds = Math.round(interval % 60);
	
	return {
		day:day,
		hours:hours,
		minutes:minutes,
		seconds:seconds,
	}
}

var d1 = new Date();
var d2 = new Date(2021, 6, 8);
var intervalTime = fn(d1, d2);
console.log(intervalTime);


这篇关于JavaScript基础——内置对象(Math对象和Date对象)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程