(十一)内置对象
1. 内置对象
- Javascript中的对象分为3种:自定义对象、内置对象、浏览器对象
- 前面两种对象是IS基础内容,属于ECMAScript ;第三个浏览器对象属于我们JS独有的,我们JS APl讲解
- 内置对象就是指JS语言自带的一些对象,这些对象供开发者使用,并提供了一些常用的或是最基本而必要的功能(属性和方法)
2. 数学对象 Math
2.1 Math 的使用
查询 MDN 文档
const arr = [3,4,11,24,89,2,34]
console.log(Math.max(...arr)); // 89
console.log(Math.PI); // 3.141592653589793
console.log(Math.max()); // -Infinity
2.1 自定义自己的 Math 对象
我们可以自定义自己的对象。
const myMath = {
PI: 3.141592654,
max: function () {
let max = arguments[0];
for (let i = 1; i < arguments.length; i++) {
max = arguments[i] > max ? arguments[i] : max;
}
return max;
},
min: function () {
let min = arguments[0];
for (let i = 1; i < arguments.length; i++) {
min = arguments[i] < min ? arguments[i] : min;
}
return min;
}
}
2.3 Math 常用方法
Math.PI // 圆周率
Math.floor() // 向下取整
Math.ceil() // 向上取整
Math.round() // 四舍五入,遇到 .5 往大了取
Math.abs() // 绝对值
Math.max() // 最大值
Math.min() // 最小值
console.log(Math.abs('-1')); // 1
console.log(Math.floor(-2.5)); // 3
console.log(Math.ceil(-2.5)); // -2
console.log(Math.round(-3.5)); // -3
console.log(Math.round(3.5)); // 4
2.4 Math.random 随机数
Math.random
方法返回一个位于区间 [0, 1)
的伪随机浮点数。
Math.random(); // 0.41713485547506424
获取闭区间 [a, b]
之间的整数:
let ran = parseInt(Math.random() * (b - a + 1)) + a;
获取前闭后开区间 [a, b)
之间的整数:
let ran = parseInt(Math.random() * (b - a)) + a;
实例:定义自己的取整函数
// [a, b)
function getRandom1(a, b) {
return parseInt(Math.random() * (b -a)) + a;
}
// [a, b]
function getRandom2(a, b) {
return parseInt(Math.random() * (b - a + 1)) + a;
}
应用:随机点名
let names = new Array('Peter', 'Murphy', 'Jack', 'Darcy', 'Alice');
console.log(names[getRandom2(0, names.length-1)]);
3. 日期对象 Date
3.1 时间格式化
Date
对象是一个构造函数,需要使用 new
来创建日期对象(实例化)。
若没有参数,则默认返回当前系统的当前时间
let date = new Date();
console.log(date);
若有参数,则返回参数里面的时间。
参数常用写法
let date = new Date();
console.log(date);
// 2021-03-15T05:39:52.204Z
let date1 = new Date(2019, 10, 1);
console.log(date1);
// 2019-10-31T16:00:00.000Z
let date2 = new Date('2019-10-1 8:8:8');
console.log(date2);
// 2019-10-01T00:08:08.000Z
一般使用以下参数形式
let date3 = new Date('2019-10-1 10:10:10');
let date4 = new Date('2019/10/1');
常用返回日期格式:
let date = new Date();
console.log(date.getFullYear()); // 2021
console.log(date.getMonth() + 1); // 3,注意得到的月份要加 1
console.log(date.getDate()); // 15
console.log(date.getDay()); // 1
实例一:返回 今天是 2021 年 3 月 15 日 周一
的日期格式。
let year = date.getFullYear();
let month = date.getMonth() + 1;
let dates = date.getDate();
let day = date.getDay();
let days = ['日', '一', '二', '三', '四', '五', '六']
console.log(`今天是 ${year} 年 ${month} 月 ${dates} 日 周${days[day]}`);
实例二:输出时分秒 15:06:09
格式化时间串。
function getTime() {
let time = new Date();
let h, m, s;
[h, m, s] = [time.getHours(), time.getMinutes(), time.getSeconds()]
function check(t) {
return t < 10 ? '0' + t : t;
}
[h, m, s] = [check(h), check(m), check(s)];
return h + ':' + m + ':' +s;
}
console.log(getTime());
3.2 时间戳(获取1971年1月1日至今过去的毫秒数)
// 1. valueOf(), getTime()
let date = new Date();
console.log(date.valueOf());
console.log(date.getTime());
// 2. 推荐写法
let date1 = +new Date();
console.log(date1);
// 3. H5新增写法
let date2 = Date.now();
console.log(date2);
4. 字符串对象
4.1 基本包装类型
- 对象才有属性和方法
- 复杂数据类型才有属性和方法
- 那么为什么简单数据类型
'aaa'
有length
属性呢? - 基本包装类型:把简单数据类型包装成复杂数据类型,这样基本数据类型也有了属性和方法
// 1. 简单数据类型包装成复杂数据类型
let temp = new String('aaa');
// 2. 把临时变量赋值给 str
str = temp;
// 3. 销毁临时变量
- 三种基本包装类型:
String
、Number
、Boolean
4.2 字符串的不可变
指的是其值不变。虽然看上去是可以改变的,但其实是地址变了,内存中开辟了一个内存空间。
4.3 根据字符串返回位置
语法
从 start
索引开始查找 c
。
str.indexOf('c', start)
4.4 根据位置返回字符
-
charAt()
str.charAt(index);
-
charCodeAt()
返回该位置的字符的 ASCII 值。一般用于判断用户按下了哪个键。str.charCodeAt(i)
-
str[index]
H5 新增写法。str[i];
4.5 拼接以及截取字符串
- 字符串拼接
str.concat(str1, str2, str3, ...)
- 获取子串,[start, start+length]
str.substr(start, length)
- 切片,前闭后开:[start, end)
str.slice(start, end)
- 获取子串,前闭后开:[start, end)
str.substring(start, end)
[!warning]
警告: 尽管String.prototype.substr()
没有严格被废弃 (as in “removed from the Web standards”), 但它被认作是遗留的函数并且可以的话应该避免使用。它并非JavaScript核心语言的一部分,未来将可能会被移除掉。如果可以的话,使用substring()
替代它.
4.6 替换、转换为数组
- 替换
replace
,只换一次,将a替换为b。str.replace('a', 'b'); str='szxszx';//szxszx str.replace('s','1');//1zxszx
- 转换为数组
split()
let str1 = 'red pink blue'; console.log(str1.split(' ')) // [ 'red', 'pink', 'blue' ] let str2 = 'red&pink&blue'; console.log(str2.split('&')) // [ 'red', 'pink', 'blue' ]
4.7 查找某个字符出现的位置和次数
// 查找某个字符出现的位置和次数
function findLocation(str, char) {
let res = {
loc: [],
count: 0
};
for (let i = 0; i < str.length; i++) {
if (str[i] === char) {
res.loc.push(i);
res.count++;
}
}
return res;
}
let ans = findLocation("abcaaadef", "a");
console.log(ans.count, ans.loc); // 4 [ 0, 3, 4, 5 ]
4.8 统计出现次数最多的字符
function findMost(str) {
let res = {};
for (const i in str) {
if (str[i] in res) {
res[str[i]]++;
} else {
res[str[i]] = 1;
}
}
let temp = -Infinity;
let ans;
for (const k in res) {
if (res[k] > temp) {
temp = res[k];
ans = k;
}
}
return [ans, temp];
};
console.log(findMost("abbcaaa")); // [ 'a', 4 ]