1、千分位分隔符
const toDecimalMark = num => num.toLocaleString("en-US");
console.log(toDecimalMark(12305030388.9087))
2、时间戳转时间
const setTime = tiemStamp => new Date(parseInt(timeStamp) * 1000).toLocaleString().replace(/[/]/g,'-');
console.log(setTime(1535932800))
3、时间转时间戳
const timeStamp = time => new Date(time).getTime();
console.log(timeStamp('2019-03-19 11:55:00'))
4、去除空格
const removeSpace = str => str.replace(/\s+/g,'')
let str = '1 2 3 4'
console.log(removeSpace(str))
5、检测类型
const typeOf = str=> Object.prototype.toString.call(str) == '[object String]'
let str = '3123'
console.log(typeOf(str))
6、数字简化为“万”
function unitConvert(num){
let moneyUnits = ['元','万元','亿元','万亿'];
let dividend = 10000;
let curentNum = num; //转换数字
let curentUnit = moneyUnits[0]; //转换单位
let len = moneyUnits.length;
for(var i = 0; i < len; i++) {
curentUnit = moneyUnits[i];
if(strNumSize(curentNum) < 5) {
break;
}
curentNum = curentNum / dividend;
}
let m = {num: 0,unit: ""}
m.num = curentNum.toFixed(2);
m.unit = curentUnit;
return m;
}
function strNumSize(tempNum) {
var stringNum = tempNum.toString();
var index = stringNum.indexOf(".");
var newNum = stringNum;
if(index != -1) {
newNum = stringNum.substring(0, index);
}
return newNum.length;
}
unitConvert(1000000)
7、数组去重
(1)
let arrList = [1,2,3,1,3,33,6,2];
const removeRepeat = arr => [...new Set(arr)]
console.log(removeArr(arrList))
(2)
let arrList = [1,2,3,1,3,33,6,2];
let newArr = [];
let len = arrList.length
for(let i=0;i
8、出现最多次数的字符串,出现多少次
let str = "qwertyuiopqqqasdf"
function maxstringload(str){
let obj = {}
let len = str.length
for(let i=0;i
9、数组排序
(1)
let arr = [17,2,47,3,5,9,3,4,11,4,24]
const sortArr = arr => arr.sort((prve,next) => prve-next);
console.log(arr)
(2)
function bubbleSort(arr) {
let len = arr.length;
for(let i = 0; i < len; i++) {
for(let j = 0; j < len - 1 - i; j++) {
if(arr[j] > arr[j + 1]) { //相邻元素两两对比,如果前一个数比后一个大,就交换位置
let temp = arr[j + 1]; //元素交换
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
let arr = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48];
console.log(bubbleSort(arr));
10、深拷贝
(1)
const clone = obj => obj.JSON.parse(JSON.stringify(obj));
const clone = obj => obj.JSON.stringify(JSON.parse(obj))
(2)
const perfectClone = obj => {
if(obj == null){
return 'unKonwn';
}
if(typeof obj !== 'object'){
return obj
}
if(obj.constructor === Date){
return new Date(obj)
}
const newObj = new obj.constructor();
for(let key in obj){
if(obj.hasOwnProperty(key)){
const val = obj[key]
newObj[key] = typeof val === 'object' ? argument.call(val) : val;
}
}
return newObj
}
11、浅拷贝
const shallowClone = obj => Object.assign({},obj)
12、随机数
Math.random();//随机生成0到1的数字
Math.floor(Math.random() * 可能只的总数 + 第一个可能的值)
eg:Math.floor(Math.random() * 9 + 2); // 生成2到10的值,包括2和10
即:
Math.floor(Math.random()*(最大值 - 最小值 +1) + 最小值);//随机生成[n,m]的随机整数
13、数组扁平化
function flat(arr){
let newArr = [];
let len = arr.length
for(let i=0;i }
return newArr
}
let arr = [1,2,[3,4,[5,6],7],8,9];
console.log(flat(arr))
待续。。。