前言
该文章记录一些JS内置对象知识,慢慢将会添加更多知识,所有内容均从网上整理而来,加上自己的理解做一个整合,方便工作中使用。
一、Math
//向下取整
Math.floor(1.9) // 1
//向上取整
Math.ceil(1.0000001) // 2
//去除小数位==向下取整
Math.trunc(1.0001) // 1
//求最大值
Math.max(...[1, 2, 3, 4, 5, 6]) //6
Math.max(1, 2, 3, 4, 5, 6) //6
//求最小值
Math.min(...[1, 2, 3, 4, 5, 6]) // 1
//随机数,生成0~1;包括0(实测不会到0),不包括1
Math.random() // (0 ~ 1)
//求两个数之间的随机数
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
//求两个数之间的随机整数,不含最大值,含最小值
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
//求两个数之间的随机整数,含最大值,含最小值
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
}
二、Date
1. Date构造函数
//返回Date对象,4种写法
// 1.不传参-返回当前时间的Date对象
new Date()
// 2.传参-返回指定时间的Date对象
//2-1. new Date(dateString)
new Date('2020-2-20 10:20:30')
new Date('2020') //自动补齐1月1日08:00:00时
//2-2. new Date(年,月(0~11),[日,小时,分钟,秒,毫秒]),年月必填参数
new Date(2020, 1)
new Date(2020, 1, 10, 10, 12, 30)
2. Date静态方法
//静态方法
//1. 返回自 1970年1月1日到当前时间的毫秒数
Date.now()
3. Date实例方法
// 1.getTime(): 将Date对象转成时间戳
let time = new Date('2020-10-12')
console.log( time.getTime() ) //1602460800000
三、String
1. String实例方法
- 字符串填充
//字符串填充,返回一个新的字符串,而不修改原始字符串
//padStart(targetLength, padString) 从左侧开始填充
//padEnd(targetLength, padString) 从右侧开始填充
//targetLength:当前字符串需要填充到的目标长度。如果这个数值小于当前字符串的长度,则返回当前字符串本身。
//padString:填充字符串。如果字符串太长,使填充后的字符串长度超过了目标长度,则只保留最左侧的部分,其他部分会被截断。
let str = 'abc'
console.log(str.padStart(4, 'F')) //输出Fabc
console.log(str.padEnd(5, 'FFFFFF')) //输出abcFF
- 字符串清除两端空白
//从字符串的两端清除空格,返回一个新的字符串,而不修改原始字符串
str.trim()
//删除字符串末尾的空白字符,返回一个新的字符串,而不修改原始字符串
str.trimEnd()
//删除字符串开头的空白字符,返回一个新的字符串,而不修改原始字符串
str.trimStart()