一、js对象常用函数
String对象
toString():转换为字符串
split(‘.’):以
.分割- 返回值:数组
substring(a,b):字符串截取 截取索引a和b之间的部分
- 返回值:字符串
parseFloat():转化为浮点数
parseInt( ): 转化为int类型数
trim(): 去除字符串中的空格
1
2
3let content = ' hdfak hfkahd'
content.trim()
返回值: 'hdfakhfkahd'
Math对象
- Math.random(): 获取随机数 范围为:[0,1)
- Math.floor( ): 向下取整
- Math.ceil( ):向上取整
Array对象
reduce()
该函数相当于遍历数组,且可以保存每次操作的结果,提供给下次操作使用
参数:函数
1
2
3
4reduce((pre, cur, index, array) => {
}, Initial)
//initial: 传入的初始值即pre的初始值- 函数四个参数含义
1
2
3
41、previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
2、currentValue (数组中当前被处理的元素)
3、index (当前元素在数组中的索引)
4、array (调用 reduce 的数组, 即原始数组)案例
1
2
3
4
5
6var arr = [1, 2, 3, 4];
var sum = arr.reduce(function(prev, cur, index, arr) {
console.log(prev, cur, index);
return prev + cur;//遍历数组的循环体
}, 0)//这里的0是传入的初始值
console.log(arr, sum);forEach()
- 遍历数组
- 参数:函数
- 案例
1
2
3line.forEach((item) => { //item 为 line数组中的元素 forEach方法
let time = item.match()
})unshift() : 加在数组头
push() : 加在结尾
splice(): 根据索性在数组中删除或添加元素
- 语法: array.splice(index,howmany,item1,…..,itemX)
- 参数:
- index: 必填。规定从何处添加/删除元素。 该参数是开始插入和(或)删除的数组元素的下标,必须是数字。
- 可选。规定应该删除多少元素。必须是数字,但可以是 “0”。
如果未规定此参数,则删除从 index 开始到原数组结尾的所有元素。 - 可选。要添加到数组的新元素
- 返回值: array——返回删除部分的数组 而不是删除之后的 数组
filter(): 使用filter时,若有{}则要加return
- filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
1
2
3
4
5
6
7
8
9
10
11var intersection = function(nums1, nums2) {
let set1 = new Set(nums1)
////此处只是省去了return
//函数内部语句只有一句 ---- 可以省去{} 若有return 也可以省去return
return [...set1].filter(item => nums2.includes(item))
};
var intersection = function(nums1, nums2) {
let set1 = new Set(nums1)
// 使用filter时,若有{}则要加return
return [...set1].filter(item => {return nums2.includes(item)})
};indexOf(): 查找项的下标 , 返回查到第一个项的下标, 若没有找到则返回 -1
sort(): 排序 返回排序好的数组
1
2
3
4
5
6
7
8// 升序
const res = array.sort((a,b)=>{
return a-b
})
// 降序
const res = array.sort((a,b)=>{
return b-a
})push() : 向数组添加元素, 注意返回值是添加元素后的数组长度
Number对象
toFixed(n): 保留小数点后n位
1
(58 * 1.6).toFixed(2)
Date对象
1 | //返回值类型为: "2020-02-17T09:58:45.123Z" |
- 不同时间类型的转换
1 | //时间戳-----> Date()对象 |
1 | //readObj.createTime为字符串 : "2020-02-17T09:58:45.123Z" 将字符串类型时间转化以毫秒为单位的时间 |
JSON
JSON.stringify(): 将对象转成字符串
JSON.parse(): 将字符串转成对象
定时器
- setTimeout() 执行一次
1 | setTimeout(() => { |
- setInterval() 执行多次
1 | setInterval(async () => { |