欢迎大家关注我的微信公众号,不定时更新
使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}
引用后就可以直接使用了!
001.输入一个值,返回其数据类型
type = para => {
return Object.prototype.toString.call(para).slice(8,-1)
}
复制代码
002.冒泡排序
升序 bubbleAsSort()
bubbleAsSort = arr => {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
let temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
复制代码
降序 bubbleDeSort()
bubbleDeSort = arr => {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] < arr[j + 1]) {
let temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
复制代码
003.选择排序
升序 selectAsSort()
selectAsSort = arr => {
let minIndex, temp;
for (let i = 0; i < arr.length - 1; i++) {
minIndex = i;
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
return arr;
}
复制代码
降序 selectDeSort()
selectDeSort = arr => {
let minIndex, temp;
for (let i = 0; i < arr.length - 1; i++) {
minIndex = i;
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] > arr[minIndex]) {
minIndex = j;
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
return arr;
}
复制代码
004.插入排序
升序 insertAsSort()
insertAsSort = arr => {
let current, preIndex;
for (let i = 1; i < arr.length; i++) {
current = arr[i];
preIndex = i - 1;
while (preIndex >= 0 && arr[preIndex] > current) {
arr[preIndex + 1] = arr[preIndex];
preIndex--;
}
arr[preIndex + 1] = current;
}
return arr;
}
复制代码
降序 insertDeSort()
insertDeSort = arr => {
let current, preIndex;
for (let i = 1; i < arr.length; i++) {
current = arr[i];
preIndex = i - 1;
while (preIndex >= 0 && arr[preIndex] < current) {
arr[preIndex + 1] = arr[preIndex];
preIndex--;
}
arr[preIndex + 1] = current;
}
return arr;
}
复制代码
005.阶乘
factorial = num => {
let count = 1;
for (let i = 1; i <= num; i++) {
count *= i;
}
return count;
}
复制代码
006.两个数之间累乘
multBetride = (x, y) => {
let count;
if (x < y) {
count = x;
for (let i = x + 1; i <= y; i++) {
count *= i;
}
return count;
} else {
count = y;
for (let i = y + 1; i <= x; i++) {
count *= i;
}
return count;
}
}
复制代码
007.累加
()里面可以放N个实参
function cumsum() {
let sum = 0;
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
复制代码
008.计时器(计算代码块(函数)执行时间)
无参 computeTime(f)
computeTime = code => {
let startTime = new Date().getTime();
code();
let endTime = new Date().getTime();
let time = endTime - startTime;
return time;
}
复制代码
有参 computeTime(f)
使用方法:computeTime(f,参数1,参数2......)
computeTime = f => {
let startTime = new Date().getTime();
let p = [];
for (let i = 1; i < arguments.length; i++) {
p.push(arguments[i])
}
f.apply(null, p)
let endTime = new Date().getTime();
let Time = endTime - startTime;
return Time;
}
复制代码
009.数组去重
arrDemp1 = arr => {
let newArr = [];
let m = {};
for (let i = 0; i < arr.length; i++) {
let n = arr[i];
if (m[n]) {
} else {
newArr.push(arr[i]);
m[n] = true;
}
}
return newArr;
}
//遍历数组法
arrDemp2 = arr => {
let temp = [];
for (let i = 0; i < arr.length; i++) {
//indexOf()方法可返回某个指定的字符串或数组值在字符串或数组中首次出现的位置,若不在其中则返回-1
if (temp.indexOf(arr[i]) === -1)
temp.push(arr[i]);
}
return temp;
}
//排序法
arrDemp3 = arr => {
let temp = [];
arr.sort();
temp.push(arr[0]);
//因为数组已经经过排序,所以重复元素一定相邻,判断当前数组第i个元素与temp的最后一个元素是否相等,不相等时才复制元素
for (let i = 1; i < arr.length; i++) {
if (arr[i] != temp[temp.length - 1])
temp.push(arr[i]);
}
return temp;
}
//对象法
arrDemp4 = arr => {
let temp = [];
let json = {};
//将当前数组的元素值当作对象的属性,遍历数组,比对对象,如果对象的这个属性不存在则将当前数组元素复制到临时数组,并添加该属性且将属性值赋值为1
for (let i = 0; i < arr.length; i++) {
if (!json[arr[i]]) {//如果对象没有该属性
temp.push(arr[i]);
json[arr[i]] = 1;//添加属性,将属性值赋值为1
}
}
return temp;
}
复制代码
也可以使用ES6中的new Set
,一步到位
let arr = [1,2,3,5,4,5,4,3,6]
let arrDemp = new Set(arr) //arrDemp是一个对象
let newArr = [...arrDemp] //把arrDemp转化成数组
console.log(newArr);
复制代码
010.数组对象去重
将对象数组中属性相同的项去重
/*
* objArr 对象数组
* para 将要进行去重的字段(String类型)
*/
测试数据:
let objArr = [{ name: ‘a‘, age: 1 }, { name: ‘a‘, age: 2 }, { name: ‘b‘, age: 2 }]
console.log(objArrDemp1(objArr,‘name‘)); // [ { name: ‘a‘, age: 1 }, { name: ‘b‘, age: 2 } ]
console.log(objArrDemp1(objArr,‘age‘)); // [ { name: ‘a‘, age: 1 }, { name: ‘a‘, age: 2 } ]
objArrDemp1 = (objArr, para) => {
let result = [];
let temp = {};
for (let i = 0; i < objArr.length; i++) {
let parameter = objArr[i][para];
if (temp[parameter]) {
continue;//不继续执行接下来的代码,跳转至循环开头
}
temp[parameter] = true;//为temp添加此属性(parameter)且将其值赋为true
result.push(objArr[i]);//将这一项复制到结果数组result中去
}
return result;
}
objArrDemp2 = (objArr, para) => {
let hash = {};
//reduce方法有两个参数,第一个参数是一个callback,用于针对数组项的操作;第二个参数则是传入的初始值,这个初始值用于单个数组项的操作。
objArr = objArr.reduce(function (item, next) {//这是针对数组项操作的函数,对于每个数组项,reduce方法都会将其调用一次
hash[next[para]] ? ‘‘ : hash[next[para]] = true && item.push(next);
return item;
}, []);//初始值是一个空对象,使用reduce方法返回的是空对象通过叠加执行之后的结果
return objArr;
}
复制代码
011.统计数组中各个元素出现的次数
staArrNum = arr => {
let obj = {};
for (let i = 0; i < arr.length; i++) {
let m = arr[i];
if (obj.hasOwnProperty(m)) {
obj[m] += 1;
} else {
obj[m] = 1;
}
}
return obj;
}
let arr = [1, 2, 3, 6, 5, 3, 2, 1, 2, 3, 2, 1]
console.log(staArrNum(arr)); // { ‘1‘: 3, ‘2‘: 4, ‘3‘: 3, ‘5‘: 1, ‘6‘: 1 }
复制代码
012.在数组中找指定的元素,返回下标
arrFinNum = function (arr,num) {
let index = -1;
for (let i = 0; i < arr.length; i++) {
if (num == arr[i]) {
index = i;
break;
}
}
return index;
}
let arr = [1,2,3,4,5,6]
console.log(arrFinNum(arr,4)); // 3
复制代码
013.删除数组中的元素
delArrNum = (arr,val) => {
let index = arrFinNum(arr, val) //调用了前面自行添加的arrFinNum方法
if (index != -1) {
return arr.splice(index, 1);
}
}
复制代码
示例
let arr = [1, 2, 3, 4, 5, 6]
arrFinNum = (arr, num) => {
let index = -1;
for (let i = 0; i < arr.length; i++) {
if (num == arr[i]) {
index = i;
break;
}
}
return index;
}
delArrNum = (arr,val) => {
let index = arrFinNum(arr, val) //调用了前面自行添加的arrFinNum方法
if (index != -1) {
return arr.splice(index, 1);
}
}
console.log(delArrNum(arr,2)); // [ 2 ]
复制代码
014.数字超过9显示省略号
num_filter = val =>{
val = val?val-0:0;
if (val > 9 ) {
return "…"
}else{
return val;
}
}
复制代码
015.数字超过99显示99+
ninenum_filter = val =>{
val = val?val-0:0;
if (val > 99 ) {
return "99+"
}else{
return val;
}
}
复制代码
016.银行卡号分割
bank_filter = val =>{
val += ‘‘;
val = val.replace(/(\s)/g,‘‘).replace(/(\d{4})/g,‘$1 ‘).replace(/\s*$/,‘‘);
return val;
}
复制代码
017.二分查找
//非递归实现
binarySearch = (arr, key) => {
let high = arr.length - 1,
low = 0;
while (low <= high) {
let m = Math.floor((high + low) / 2);
if (arr[m] == key) {
return m;
}
if (key > arr[m]) {
low = m + 1;
} else {
high = m - 1;
}
}
return false;
}
let arr = [-1, 1, 3, 4, 5, 8, 32, 234, 12, 42];
console.log(binarySearch(arr, 4));
复制代码
//递归实现
binarySearch = (arr, low, high, key) => {
if (low > high) {
return -1;
}
let mid = parseInt((high + low) / 2);
if (arr[mid] == key) {
return mid;
} else if (arr[mid] > key) {
high = mid - 1;
return binarySearch(arr, low, high, key);
} else if (arr[mid] < key) {
low = mid + 1;
return binarySearch(arr, low, high, key);
}
};
let arr = [-1, 1, 3, 4, 5, 8, 32, 234, 12, 42];
console.log(binarySearch(arr, 0, 13, 5));
复制代码
018.防抖与节流
/**
* 函数防抖 (只执行最后一次点击)
*/
Debounce = (fn, t) => {
let delay = t || 500;
let timer;
return function () {
let args = arguments;
if(timer){
clearTimeout(timer);
}
timer = setTimeout(() => {
timer = null;
fn.apply(this, args);
}, delay);
}
};
/*
* 函数节流
*/
Throttle = (fn, t) => {
let last;
let timer;
let interval = t || 500;
return function () {
let args = arguments;
let now = +new Date();
if (last && now - last < interval) {
clearTimeout(timer);
timer = setTimeout(() => {
last = now;
fn.apply(this, args);
}, interval);
} else {
last = now;
fn.apply(this, args);
}
}
};
复制代码
019.深拷贝
deepClone = source => {
const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象
for (let keys in source) { // 遍历目标
if (source.hasOwnProperty(keys)) {
if (source[keys] && typeof source[keys] === ‘object‘) { // 如果值是对象,就递归一下
targetObj[keys] = source[keys].constructor === Array ? [] : {};
targetObj[keys] = deepClone(source[keys]);
} else { // 如果不是,就直接赋值
targetObj[keys] = source[keys];
}
}
}
return targetObj;
}
let str1 = {
arr: [1, 2, 3],
obj: {
key: ‘value‘
},
fn: function () {
return 1;
}
};
let str3 = deepClone(str1);
console.log(str3 === str1); // false
console.log(str3.obj === str1.obj); // false
console.log(str3.fn === str1.fn); // true
复制代码
020.获取视口尺寸
需要在HTML文件中运行
function getViewportOffset() {
if (window.innerWidth) {
return {
w: window.innerWidth,
h: window.innerHeight
}
} else {
// ie8及其以下
if (document.compatMode === "BackCompat") {
// 怪异模式
return {
w: document.body.clientWidth,
h: document.body.clientHeight
}
} else {
// 标准模式
return {
w: document.documentElement.clientWidth,
h: document.documentElement.clientHeight
}
}
}
}
复制代码
021.数字前补零
/**
* num为你想要进行填充的数字
* length为你想要的数字长度
*/
//迭代方式实现
padding1=(num, length)=> {
for(let len = (num + "").length; len < length; len = num.length) {
num = "0" + num;
}
return num;
}
//递归方式实现
padding2=(num, length) =>{
if((num + "").length >= length) {
return num;
}
return padding2("0" + num, length)
}
//转为小数
padding3=(num, length)=> {
let decimal = num / Math.pow(10, length);
//toFixed指定保留几位小数
decimal = decimal.toFixed(length) + "";
return decimal.substr(decimal.indexOf(".")+1);
}
//填充截取法
padding4=(num, length)=> {
//这里用slice和substr均可
return (Array(length).join("0") + num).slice(-length);
}
//填充截取法
padding5=(num, length)=> {
let len = (num + "").length;
let diff = length+1 - len;
if(diff > 0) {
return Array(diff).join("0") + num;
}
return num;
}
复制代码
022.字符替换
可以替换任意数字和符号
/**
* str 表示将要替换的字符串
* l 表示你将要替换的字符
* r 表示你想要替换的字符
*/
transFormat = (str, l, r) => {
let reg = new RegExp(l, ‘g‘) // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
console.log(transFormat(‘2019-12-13‘, ‘-‘, ‘/‘)); // 2019/12/13
console.log(transFormat(‘2019-12-13‘, ‘-‘, ‘‘)); // 20191213
复制代码
023.在字符串指定位置插入字符
/**
* character 原字符串(String)
* site 要插入的字符的位置 (Number)
* newStr 想要插入的字符 (String)
*/
insertStr = (character, site, newStr) => {
return character.slice(0, site) + newStr + character.slice(site);
}
console.log(insertStr(‘20191217‘,4,‘-‘)); // 2019-1217
复制代码
024.字符串反转处理分割
/**
* str 是你将要进行处理的字符串(String)
* under 是你根据什么字符处理(String)
* event 是你根据什么字符把处理结果分割(String)
*/
keyCharacterMap = (str,under,event) => {
return str.split(under).reverse().join(event)
}
console.log(keyCharacterMap(‘hello world‘,‘‘,‘‘)); // dlrow olleh
console.log(keyCharacterMap(‘hello world‘,‘ ‘,‘-‘)); // world-hello
复制代码
025.格式转换:base64转file
/**
* base64 base64
* filename 转换后的文件名
*/
base64ToFile = (base64, filename) => {
let arr = base64.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {
type: mime
});
}
复制代码
026.格式转换:base64转blob
base64ToBlob = base64 => {
let arr = base64.split(‘,‘),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
};
复制代码
027.格式转换:blob转file
blobToFile = (blob, fileName) => {
blob.lastModifiedDate = new Date();
blob.name = fileName;
return blob;
};
复制代码
028.截取指定字符之前之后的字符串
// 截取指定字符之前的字符串
beforeStrSub = (str, char) => {
return str.split(char)[0]
}
// 截取指定字符之后的字符串
afterStrSub = (str, char) => {
return str.split(char)[1]
}
// 测试数据
let str = ‘abc:de;fghi.jk‘;
console.log(beforeStrSub(str, ‘;‘)); // abc:de
console.log(afterStrSub(str, ‘f‘)); // ghi.jk
复制代码
029.截取指定字符之间的字符串
/**
* str 要截取的字符串 (String)
* start 字符串截取的开始位置 (String)
* end 字符串截取的结束位置 (String)
*/
betweenStrSub = (str, start, end) => {
temp = str.split(start, 2);
content = temp[1].split(end, 2);
return content[0];
}
// 测试数据
let str = ‘abc:de;fghi.jk‘;
console.log(betweenStrSub(str, ‘:‘, ‘.‘)); // de;fghi
console.log(betweenStrSub(str, ‘bc‘, ‘k‘)); // :de;fghi.j
console.log(betweenStrSub(str, ‘:‘, ‘k‘)); // de;fghi.j
复制代码
030.获取地址栏传递过来的参数
/**
* name为地址栏传递过来的字段名
*/
getQueryString = name => {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
let r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
// 测试
// http://localhost:3306/admin?id=111&name=xxx
// console.log(getQueryString(‘id‘)); // 111
// console.log(getQueryString(‘name‘)); // xxx
复制代码
031.字符串反转
/**
* str 要反转的字符串
*/
strInversion = str => {
str = str + ‘‘;
let newStr=[];
newStr=str.split("").reverse().join("");
return newStr
}
// 测试数据
console.log(strInversion("I Love You!")); // !uoY evoL I
复制代码
032.对象处理为数组对象
/**
* obj 需要处理的对象
*/
objToArrObj = obj => {
let arr = []
for(let i in obj){
arr.push({[i]:obj[i]})
}
return arr
}
// 测试数据
let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}
console.log(objToArrObj(obj));
/*
[
{ 20180410: 5 },
{ 20180411: 13 },
{ 20180412: 26 },
{ 20180413: 16 }
]
*/
复制代码
033.通过键查找对象数组中对应的下标、键、值
/**
* arr 对象数组
* index 要查找的键名
*/
objArrHandle = (arr,keyName) => {
let sub = arr.findIndex(item=>item[keyName])
let obj = arr[sub]
let key = Object.keys(obj)[0]
let value = obj[Object.keys(obj)]
return ‘下标:‘+sub+‘ 键:‘+key+‘ 值:‘+value
}
// 测试数据
let arr = [{ 20180410: 5 },{ 20180411: 13 },{ 20180412: 26 },{ 20180413: 16 }]
console.log(objArrHandle(arr,20180412)); // 下标:2 键:20180412 值:26
作者:YXi
链接:https://juejin.im/post/5deb2cdf518825122671b637
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。