js开发技巧集锦

js有很多开发技巧,把它归为以下几点:

  • String Skill:字符串技巧
  • Number Skill:数值技巧
  • Boolean Skill:布尔技巧
  • Array Skill:数组技巧
  • Object Skill:对象技巧
  • Function Skill:函数技巧
  • DOM Skill:DOM技巧

String Skill:

 1,格式化金钱

const ThousandNum = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
const money = ThousandNum(20190214);

2,生成随机ID:
const RandomId = len => Math.random().toString(36).substr(3, len);
const id = RandomId(10);
// id => "jg7zpgiqva"

3,生成随机HEX色值:
const RandomColor = () => "#" + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0");
const color = RandomColor();
// color => "#f03665"

4,生成星级评分:
const StartScore = rate => "★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);
const start = StartScore(3);
// start => "★★★"

5,查询URL参数
const params = new URLSearchParams(location.search.replace(/\?/ig, "")); // location.search = "?name=young&sex=male"
params.has("young"); // true
params.get("sex"); // "male"


Number Skill:
1,补零
const FillZero = (num, len) => num.toString().padStart(len, "0");
const num = FillZero(169, 5);
// num => "00169"

2,转数值(只对null、""、false、数值字符串有效)
const num1 = +null;
const num2 = +"";
const num3 = +false;
const num4 = +"169";
// num1 num2 num3 num4 => 0 0 0 169

3,时间戳
const timestamp = +new Date("2019-02-14");
// timestamp => 1550102400000

4,精确小数
const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal;
const num = RoundNum(1.69, 1);
// num => 1.7

5,判断奇数偶数
const OddEven = num => !!(num & 1) ? "odd" : "even";
const num = OddEven(2);
// num => "even"

6,取最小最大值
const arr = [0, 1, 2];
const min = Math.min(...arr);
const max = Math.max(...arr);
// min max => 0 2
 Boolean Skill:
1,判断数据类型
function DataType(tgt, type) {
    const dataType = Object.prototype.toString.call(tgt).replace(/\[object (\w+)\]/, "$1").toLowerCase();
    return type ? dataType === type : dataType;
}
DataType("young"); // "string"
DataType(20190214); // "number"
DataType(true); // "boolean"
DataType([], "array"); // true
DataType({}, "array"); // false

2,是否为空数组
const arr = [];
const flag = Array.isArray(arr) && !arr.length;
// flag => true


3,是否为空对象
const obj = {};
const flag = DataType(obj, "object") && !Object.keys(obj).length;
// flag => true


Array Skill:
1,数组克隆
const _arr = [0, 1, 2];
const arr = [..._arr];
// arr => [0, 1, 2]

2,数组合并
const arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
const arr = [...arr1, ...arr2];
// arr => [0, 1, 2, 3, 4, 5];

3,数组去重
const arr = [...new Set([0, 1, 1, null, null])];
// arr => [0, 1, null]

4,数组混淆
const arr = [0, 1, 2, 3, 4, 5].slice().sort(() => Math.random() - .5);
// arr => [3, 4, 0, 5, 1, 2]

5,清空数组
const arr = [0, 1, 2];
arr.length = 0;
// arr => []

6,数组截断
const arr = [0, 1, 2];
arr.length = 2;
// arr => [0, 1]

7,交换赋值
let a = 0;
let b = 1;
[a, b] = [b, a];
// a b => 1 0

8,过滤空值(undefined、null、""、0、false、NaN)
const arr = [undefined, null, "", 0, false, NaN, 1, 2].filter(Boolean);
// arr => [1, 2]


Object Skill
1,克隆对象
const _obj = { a: 0, b: 1, c: 2 }; // 以下方法任选一种
const obj = { ..._obj };
const obj = JSON.parse(JSON.stringify(_obj));
// obj => { a: 0, b: 1, c: 2 }

2,合并对象
const obj1 = { a: 0, b: 1, c: 2 };
const obj2 = { c: 3, d: 4, e: 5 };
const obj = { ...obj1, ...obj2 };
// obj => { a: 0, b: 1, c: 3, d: 4, e: 5 }

3,删除对象无用属性
const obj = { a: 0, b: 1, c: 2 }; // 只想拿b和c
const { a, ...rest } = obj;
// rest => { b: 1, c: 2 }


Function Skill
1,函数自执行
const Func = function() {}(); // 常用

(function() {})(); // 常用
(function() {}()); // 常用
[function() {}()];

+ function() {}();
- function() {}();
~ function() {}();
! function() {}();

new function() {};
new function() {}();
void function() {}();
typeof function() {}();
delete function() {}();

1, function() {}();
1 ^ function() {}();
1 > function() {}();


DOM Skill
1,显示所有DOM边框
[].forEach.call($$("*"), dom => {
    dom.style.outline = "1px solid #" + (~~(Math.random() * (1 << 24))).toString(16);
});

2,过滤XSS
function FilterXss(content) {
    let elem = document.createElement("div");
    elem.innerText = content;
    const result = elem.innerHTML;
    elem = null;
    return result;
}
 
 
 


 
 
posted @ 2021-05-17 11:55  5Clay  阅读(49)  评论(0编辑  收藏  举报