JS系列之”好用的Api“
本篇文章主要盘点一些冷门或新颖的JSAPI。
JS APi系列第一弹
前言
最近一段时间比较忙,好久没更新文章了,本篇文章主要是分享一些js原生自带的API系列,也许它能在你实际项目开发中减少你的代码量,让它看起来更优雅些也说不定呢~
一 ES2023中的新特性
在ES2023前,常用的数组操作方法中 reverse 、sort、splice 它们的作用分别是翻转数组,排序,通过下标删除元素,或替换元素,它们的特点是都会改变原数组。
let arr = [1, 3, 2 , 4, 7, 6]
arr.reverse();
// 返回结果:[6, 7, 4, 2, 3, 1]
console.log(arr);
// 输出结果:[6, 7, 4, 2, 3, 1]
arr.sort((a, b) => a -b);
// 返回结果:[1, 2, 3, 4, 6, 7]
console.log(arr)
// 输出结果:[1, 2, 3, 4, 6, 7]
arr.splice(1, 1, 'a');
// 返回结果:[1, 'a', 3, 4, 6, 7]
console.log(arr);
// 输出结果:[1, 'a', 3, 4, 6, 7]在ES2023中推出了toReversed、toSorted、toSpliced,他们同样具备与之对应的功能,但它们不会改变原数组。
let arr = [1, 3, 2 , 4, 7, 6]
arr.toReversed(); // 对应翻转数组
// 返回结果:[6, 7, 4, 2, 3, 1]
console.log(arr)
// 输出结果:[1, 3, 2, 4, 7, 6]
arr.toSorted();
// 返回结果:[1, 2, 3, 4, 6, 7]
console.log(arr);
// 输出结果: [1, 3, 2, 4, 7, 6]
arr.toSpliced(1, 1, 'aaa');
// 返回结果:[1, 'aaa', 2, 4, 7, 6]
console.log(arr);
// 输出结果:[1, 3, 2, 4, 7, 6]二 快速生成随机ID
通过随机函数 + toString生成一个随机ID。
// 核心代码
Math.random().toString(16).replace(".", '');
Math.random().toString(16).replace(".", '')
// '0d166f02ee9d77'
Math.random().toString(16).replace(".", '')
// '0af5864f9c5d48'
Math.random().toString(16).replace(".", '')
// '04b299e6a2e6b1'
Math.random().toString(16).replace(".", '')
// '084264ac0af84f'三 填充数组
有的时候我们需要生成一些假数据用于测试,使用 fill 实现自动填充功能,在fill()中传递参数用于填充数组内容。
new Array(12).fill(1);
// 得到:[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
new Array(4).fill("").map((_, i) => ({
name: i,
sex: 0,
id: Math.random().toString(16).replace('.', '')
}))
// 得到如下结果
[
{
"name": 0,
"sex": 0,
"id": "01ece47484ad18"
},
{
"name": 1,
"sex": 0,
"id": "0f3d65fcaf022"
},
{
"name": 2,
"sex": 0,
"id": "0a76ad094e57d4"
},
{
"name": 3,
"sex": 0,
"id": "028305af919ffa"
}
]四 填充字符串
利用padEnd、padStart 分别向字符串的尾部和头部添加数据,padEnd和padStart 接收两个参数,第一个参数是长度,第二个参数是填充内容,它不会改变原数据。
举例:str = "aa",现在str的长度为2,使用padEnd(5, 'b'),结果为5 - str自身的长度,填充内容为'b'.slice(0, 5 - str),结果为“aabbb”,值得注意的是,
let str = "aa";
str.padEnd(5, 'v')
// 返回结果:'aavvv'
str.padStart(5, '1')
// 返回结果:'111aa'本网站所用图片均来自互联网,如果存在侵权请练习删除。
若感觉本文对您有所帮助请点个赞再走吧~
