这是我参与更文挑战的第4天,活动详情查看: 更文挑战
手机号码处理
//对手机号进行中间部分加密 13612312312 => 136 **** 3647
function phoneStyle(phonestr){
phonestr = phonestr+'';
if(!phone || phone.length != 11) return '输入的是非法手机号!'
return phonestr.substring(0,3)+" **** "+phonestr.substring(7,11)
}
phoneStyle2(13612312312) //"136 **** 2312"
//手机号分隔或空格 13612312312 => 136-1231-2312
function phoneStyle(phone,type) {
phone = phone + '';
if (!phone || phone.length != 11) return '输入的是非法手机号!'
return phone.replace(/(?=(\d{4})+$)/g, type);
}
phoneStyle(13612312312,"-")
数字处理
//只能输入一个小数点,第一位不能为小数点,保留两位小数,为正数
value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$')
.replace(/\./g, '').replace('$#$', '.')
.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')
数字位数不够,进行前补字符串
function PrefixZero(num, n,type) {
return (Array(n).join(type) + num).slice(-n);
}
PrefixZero(9, 3,0)//009
PrefixZero(12,3,"*")//*12
去除字符串指定字符
let str = 'abcd,abcd,dcab';
str = str.replace(/^(\s|ab)+|(\s|ab)+$/g, '');
// 结果: 'cd,abcd,dc'
生成随机颜色
let colorList =[];
for(let i=0;i<6;i++){
colorList.push('#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0'))
}
生成随机ID
Math.random().toString(36).substring(2)
每秒更新当前时间
setInterval(()=>document.body.innerHTML=new Date().toLocaleString())
金钱格式化
let money = '1234567890'
let format = money.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
console.log(format) // 1,234,567,890
递归求阶乘
let factorial = (n)=> (n > 1) ? n * factorial(n - 1) : n
factorial(5)//120
vue阻止事件冒泡
aaa(e) {
e.stopPropagation();
...
},
js来控制字符串的长度
/*
*比如传入的字符串太长了,导致显示问题:
* user_name = "爱尔奎利亚马拉西博德"
* user_name = ellipsisText(user_name, 5) //"爱尔奎利亚..."
*/
function ellipsisText(str, num) {
if (str && str.length >= num) {
str = str.substr(0, num) + '...'
}
return str;
}
for循环的特殊写法
for (语句 1; 语句 2; 语句 3)
{
被执行的代码块
}
//正常写法
for(let i=0;i<10;i++){
console.log(i);
}
/*在语句2中,如果返回true循环会继续执行。
在js中0,null,undefined,false,'',””作为条件判断时,其结果为false,
也就说当i–到0的时候就是false,循环就终止了。*/
//另外两种写法
for(var i=10;i--;){
console.log(i);
}
for (var i = 0, rule; rule = rules[i++];) {
//do something
}
去掉小数部分
parseInt(num)
~~num
num >> 0
num | 0
解构字符串成数组
[...'abcdefg'] //["a", "b", "c", "d", "e", "f", "g"]
允许滑动和禁止滑动
stopMove() {
document.body.style.overflow = "hidden";
document.addEventListener("touchmove", (e)=> e.preventDefault(), { passive: false });
},
Move() {
document.body.style.overflow = "";
document.removeEventListener("touchmove", (e)=> e.preventDefault(), { passive: true });
},
(?.)操作符号和?? 操作符
const user = {
name: "lf",
type: {
age: 12
},
list: [{name: "lf"}, {name: "lf1"}],
getName: function(){
return this.name;
}
}
user.name1;//报错
user?.name1;// undefined
user.type.age1;//报错
user.type?.height;// undefined
user.getName1();//报错
user.getName1?.();// undefined
user.list1[3].name;//报错
user.list1[3]?.name;// undefined
user?.name1??"lf";// lf 指定默认值
创建目录
const fs = require('fs');
const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);
createDirIfNotExists('dir1');
函数只执行一次
function once(fn) {
let called = false;
return function () {
if (!called) {
called = true;
fn.apply(this, arguments);
}
};
}
function fn() {
console.log("execution");
}
const fnOnce = once(fn);
fnOnce();
fnOnce();
fnOnce();
判断运行环境
//浏览器为true、node为false
const inBrowser = typeof window !== "undefined";
//环境为浏览器的前提下,得到浏览器用户代理商
const UA = inBrowser && window.navigator.userAgent.toLowerCase();
/*
不同的浏览器的userAgent的关键字:
IE:MSIE、Trident。
Edge、Chrome:Chrome。
Android:Android。
iOS:iPhone、iPad、iPod、iOS。
*/
const UA = inBrowser && window.navigator.userAgent.toLowerCase();
const isIE = UA && /msie|trident/.test(UA);
const isIE9 = UA && UA.indexOf("msie 9.0") > 0;
const isEdge = UA && UA.indexOf("edge/") > 0;
const isAndroid = (UA && UA.indexOf("android") > 0) || weexPlatform === "android";
const isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || weexPlatform === "ios";
const isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
const isPhantomJS = UA && /phantomjs/.test(UA);
const isFF = UA && UA.match(/firefox\/(\d+)/);
变量转字符串
function toString(val) {
function isPlainObject(obj) {
return Object.prototype.toString.call(obj) === "[object Object]";
}
if (val === null || val === undefined) return "";
if (Array.isArray(val)) return JSON.stringify(val);
if (isPlainObject(val) && val.toString === Object.prototype.toString)
return JSON.stringify(val);
return String(val);
}
const obj = {
title: "devpoint",
toString() {
return "obj";
},
};
console.log(toString(obj)); // obj
console.log(toString([1, 2, 3])); // [1, 2, 3]
console.log(toString(undefined)); // ""
console.log(toString(null)); // ""
JSON.stringify参数的利用
let data = [
{name: "悟空", sex:1, age: 30},
{name: "八戒", sex:0, age: 20},
{name: "唐僧", sex:1, age: 30}
];
//使用stringify的第二参数搞定提取数据
let new_data = JSON.stringify(data,["name","age"]);
//[{"name":"悟空","age":30},{"name":"八戒","age":20},{"name":"唐僧","age":30}]
//使用stringify的第三参数格式化string
let str_json = JSON.stringify(data,["name","sex"],"\t");
/*
[
{
"name": "悟空",
"sex": 1
},
{
"name": "八戒",
"sex": 0
},
{
"name": "唐僧",
"sex": 1
}
]
*/
报错推断
- SyntaxError(语法错误):SyntaxError是解析代码时发生的语法错误。
- ReferenceErro(引用错误):ReferenceError是引用一个不存在的变量时发生的错误。
- RangeError(范围错误):RangeError是当一个值超出有效范围时发生的错误。主要有几种情况,一是数组长度为负数,二是Number对象的方法参数超出范围,以及函数堆栈超过最大值。
- TypeError(类型错误)TypeError是变量或参数不是预期类型时发生的错误。比如,对字符串、布尔值、数值等原始类型的值使用new命令,就会抛出这种错误,因为new命令的参数应该是一个构造函数。
- URIError(URI错误):URIError是URI相关函数的参数不正确时抛出的错误,主要涉及encodeURI()、decodeURI()、encodeURIComponent()、decodeURIComponent()、escape()和unescape()这六个函数。
JSON.parse(null);
// null
JSON.parse('');//Uncaught SyntaxError: Unexpected end of JSON input
JSON.parse([]);//Uncaught SyntaxError: Unexpected end of JSON input
JSON.parse();//Uncaught SyntaxError: Unexpected token u in JSON at position 0
JSON.parse(undefined);//Uncaught SyntaxError: Unexpected token u in JSON at position 0
JSON.parse({});//Uncaught SyntaxError: Unexpected token o in JSON at position 1
JSON.parse('[1, 2, 3, 4, ]');//Uncaught SyntaxError: Unexpected token ] in JSON at position 13
JSON.parse('{"foo" : 1, }');//Uncaught SyntaxError: Unexpected token } in JSON at position 12
JSON.parse("{'foo': 1}");//Uncaught SyntaxError: Unexpected token ' in JSON at position 1
undefined.xxx();//Uncaught TypeError: Cannot read property 'xxx' of undefined
null.xxx//Cannot set property 'xxx' of null
//Invalid or unexpected token(有标点符号可能是中文)
# 扁平数据结构转Tree
let arr = [ {id: 1, name: '部门1', pid: 0},
{id: 2, name: '部门2', pid: 1},
{id: 3, name: '部门3', pid: 1},
id: 4, name: '部门4', pid: 3},
{id: 5, name: '部门5', pid: 4}
]
function arrayToTree(items) {
const result = []; // 存放结果集
const itemMap = {}; //
for (const item of items) {
const id = item.id;
const pid = item.pid;
if (!itemMap[id]) {
itemMap[id] = {
children: [],
}
}
itemMap[id] = {
...item,
children: itemMap[id]['children']
}
const treeItem = itemMap[id];
if (pid === 0) {
result.push(treeItem);
} else {
if (!itemMap[pid]) {
itemMap[pid] = {
children: [],
}
}
itemMap[pid].children.push(treeItem)
}
}
return result;
}