Math.pow(a,b)
let ans = Math.pow(2,10);
console.log(ans); // 1024
Math.random()
let ans1 = Math.random();
let ans2 = Math.random();
console.log(ans1); // 0.8127689903854909
console.log(ans2); // 0.06143377179016474
Math.sqrt()
let ans = Math.sqrt(64);
console.log(ans); // 8
Math.abs()
let ans = Math.abs(-30);
console.log(ans); // 30
Math.floor()
let ans = Math.floor(3.141592);
console.log(ans); // 3
Math.ceil()
let ans = Math.ceil(4.0000001);
console.log(); // 5
Math.round(x)
let ans = Math.round(26.853);
console.log(ans); // 27
new Date()
,若没有传入任何参数,则预设为当下时间,以函数方式呼叫 Date 时,会 return 当下时间日期的字串。
new Date()
可以放入 7 个参数,指定年、月、日、小时、分钟、秒、毫秒(按照顺序)
例如:
// 无参数,回传现在时间
console.log(new Date());
// Sat Oct 02 2021 03:47:31 GMT+0800 (台北标准时间)
let time = new Date(2021,10,2,12,35,22);
// 要注意月份是从 0 开始,所以当我们月份的参数写 10 时,结果会是 11 月。
console.log(time); // Tue Nov 02 2021 12:35:22 GMT+0800 (台北标准时间)
月份为 0-11,如果我们把月份的参数设为 12,则会自动进位变成下个年度的 1 月,例如:
let time2 = new Date(2020,12,31,12,30,33);
console.log(time2); // Sun Jan 31 2021 12:30:33 GMT+0800 (台北标准时间)
getDate()
, getDay()
, getFullYear()
, getHours()
, getMinutes()
, getMonth()
, getSeconds()
, getMilliseconds()
等。getFullYear()
return 西元几年 (yyyy)
let time = new Date();
let year = time.getFullYear();
console.log(year); // 2021
getMonth()
return 月份 (0-11)
现在是 10 月,所以会 return 9
let time = new Date();
let month = time.getMonth();
console.log(month); // 9
getDate()
return 日期 (1-31)
let time = new Date();
let date = time.getDate();
console.log(date); // 2
getDay()
return 星期几 (0-6) - 星期日:0~星期六:6
今天星期六,return 6
let time = new Date();
let day = time.getDay();
console.log(day); // 6
getHours()
return 几点 (0-23)
let time = new Date();
let hour = time.getHours();
console.log(time); // Sat Oct 02 2021 04:19:25 GMT+0800 (台北标准时间)
console.log(hour); // 4
getMinutes()
return 几分 (0-59)
let time = new Date();
let minute = time.getMinutes();
console.log(time); // Sat Oct 02 2021 04:20:17 GMT+0800 (台北标准时间)
console.log(minute); // 20
getSeconds()
return 几秒 (0-59)
let time = new Date();
let second = time.getSeconds();
console.log(time); // Sat Oct 02 2021 04:29:17 GMT+0800 (台北标准时间)
console.log(second); // 17
最後再举个例子:
假如我们想要把现在的日期转换为中文字,星期几 & 几月,可以先宣告星期和月份的阵列,再用索引值去抓
const time = new Date();
const weekday = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
const month = ["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"];
console.log(time); // Sat Oct 02 2021 04:31:40 GMT+0800 (台北标准时间)
console.log(weekday[time.getDay()]); // 星期六
console.log(month[time.getMonth()]); // 10月
参考资料:
Math - MDN
JavaScript Date Objects - w3schools
<<: Day15 - [丰收款] 撰写Django的Model,使用ORM和Heroku Postgres绑一起。
>>: JavaScript Day15 - event(2)
发表文章时,如果文章内容太长,我们会善用 <!-- more --> 这段语法,以至於让...
2022/2 Picker:Date / Time 开新档案- 建入string.xml <r...
哈喽大家好,今天看到了一个有趣的程序码片段(来源),这个function的功能就是把一个字串转为全小...
相关资讯 Parros IP:172.28.128.6 Linux IP:172.28.128.3 ...
选择在今天讲这个可能有点奇怪,但实在是不知道要在哪天讲比较适合,又很想把这篇打出来!!於是这篇文就诞...