JS项目开发中常用的一些小功能
目录
字符串技巧
1、比较时间
2、格式化money
3、生成随机ID
4、生成随机 HEX 颜色值
5、Generate star ratings
6、网址查询参数
7、字符串转数字
数字技能
7、Arrangement
8、零填充
9、转数
10、时间戳
11、精确小数
12、平价
13、取最小值最大值
14、生成范围随机数
15、 数字转字符串
布尔技能
15、短路运算符
16、确定数据类型
17、检查数组是否为空
18、满足条件时执行
19、如果非假则执行
20、数组不为空时执行
21、对象不为空时执行
阵列技能
22、克隆数组
23、合并数组
24、去重数组
25、混淆数组
26、清空数组
27、截断数组
28、交换数值
29、过滤空值
30、在数组开头插入成员
31、在数组末尾插入元素
32、计算数组成员的数量
33、解构嵌套数组成员
34、解构数组成员别名
35、解构数组成员默认值
36、获取随机数组成员
37、创建指定长度的数组
38、创建一个指定长度和相等值的数组
39、数组内所有数字求和
对象技能
39、克隆对象
40、合并对象
41、对象变量属性
42、创建一个纯空对象
43、删除对象无用属性
44、解构对象属性嵌套
45、解构对象属性别名
46、解构对象属性默认值
函数技能
47、函数自执行
48、一次性函数
49、延迟加载函数
50、检测非空参数
51、字符串创建函数
52、优雅地处理错误信息
53、优雅地处理 Async/Await 参数
54、优雅地处理多个函数返回值
DOM 技能
55、显示所有 DOM 边框
56、响应式页面
57、过滤 XSS
58、访问本地存储
其他技能
59、简写条件判断语句
60、多个或的条件判断语句
字符串技巧
1、比较时间
const time1 = "2022-03-02 09:00:00";
const time2 = "2022-03-02 09:00:01";
const overtime = time1 < time2;
// overtime => true
2、格式化money
const ThousandNum = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
const money = ThousandNum(1000000);
// money => '1,000,000'
3、生成随机ID
const RandomId = len => Math.random().toString(36).substr(3, len);
const id = RandomId(10);
// id => "xdeguewg1f"
4、生成随机 HEX 颜色值
const RandomColor = () => "#" + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0");
const color = RandomColor();
// color => "#2cbf89"
5、Generate star ratings
const StartScore = rate => "★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);
const start = StartScore(3);
// start => '★★★☆☆'
6、网址查询参数
const params = new URLSearchParams(location.search.replace(/\?/ig, "")); // location.search = "?name=test&sex=man"
params.has("test"); // true
params.get("sex"); // "man"
7、字符串转数字
const str = '404';
console.log(+str) // 404;
数字技能
7、Arrangement
用 Math.floor() 代替正数,用 Math.ceil() 代替负数
const num1 = ~~ 1.19;
const num2 = 2.29 | 0;
const num3 = 3.09 >> 0;
// num1 num2 num3 => 1 2 3
8、零填充
const FillZero = (num, len) => num.toString().padStart(len, "0");
const num = FillZero(1234, 5);
// num => "01234"
9、转数
仅对 null、“”、false、数字字符串有效
const num1 = +null;
const num2 = +"";
const num3 = +false;
const num4 = +"169";
// num1 num2 num3 num4 => 0 0 0 169
10、时间戳
const timestamp = +new Date("2022-03-22");
// timestamp => 1647907200000
11、精确小数
const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal;
const num = RoundNum(1.2345, 2);
// num => 1.23
12、平价
const OddEven = num => !!(num & 1) ? "odd" : "even";
const num = OddEven(2);
// num => "even"
13、取最小值最大值
const arr = [0, 1, 2, 3];
const min = Math.min(...arr);
const max = Math.max(...arr);
// min max => 0 3
14、生成范围随机数
const RandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
const num = RandomNum(1, 10); // 5
15、 数字转字符串
const myNumber = 403;
console.log(myNumber + ''); // '403'
布尔技能
15、短路运算符
const a = d && 1; // Fake operation, judge from left to right, return a false value when encountering a false value, and no longer execute it later, otherwise return the last true value
const b = d || 1; // Take the true operation, judge from left to right, return the true value when encountering the true value, and do not execute it later, otherwise return the last false value
const c = !d; // Returns false if a single expression converts to true, otherwise returns true
16、确定数据类型
可确定的类型:undefined、null、string、number、boolean、array、object、symbol、date、regexp、function、asyncfunction、arguments、set、map、weakset、weakmap
function DataType(tgt, type) {
const dataType = Object.prototype.toString.call(tgt).replace(/\[object (\w+)\]/, "$1").toLowerCase();
return type ? dataType === type : dataType;
}
DataType("test"); // "string"
DataType(20220314); // "number"
DataType(true); // "boolean"
DataType([], "array"); // true
DataType({}, "array"); // false
17、检查数组是否为空
const arr = [];
const flag = Array.isArray(arr) && !arr.length;
// flag => true
18、满足条件时执行
const flagA = true; // Condition A
const flagB = false; // Condition B
(flagA || flagB) && Func(); // Execute when A or B is satisfied
(flagA || !flagB) && Func(); // Execute when A is satisfied or B is not satisfied
flagA && flagB && Func(); // Execute when both A and B are satisfied
flagA && !flagB && Func(); // Execute when A is satisfied and B is not satisfied
19、如果非假则执行
const flag = false; // undefined、null、""、0、false、NaN
!flag && Func();
20、数组不为空时执行
const arr = [0, 1, 2];
arr.length && Func();
21、对象不为空时执行
const obj = { a: 0, b: 1, c: 2 };
Object.keys(obj).length && Func();
阵列技能
22、克隆数组
const _arr = [0, 1, 2];
const arr = [..._arr];
// arr => [0, 1, 2]
23、合并数组
const arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
const arr = [...arr1, ...arr2];
// arr => [0, 1, 2, 3, 4, 5];
24、去重数组
const arr = [...new Set([0, 1, 1, null, null])];
// arr => [0, 1, null]
25、混淆数组
const arr = [0, 1, 2, 3, 4, 5].slice().sort(() => Math.random() - .5);
// arr => [3, 4, 0, 5, 1, 2]
26、清空数组
const arr = [0, 1, 2];
arr.length = 0;
// arr => []
27、截断数组
const arr = [0, 1, 2];
arr.length = 2;
// arr => [0, 1]
28、交换数值
let a = 0;
let b = 1;
[a, b] = [b, a];
// a b => 1 0
29、过滤空值
空值:undefined,null,””,0,false,NaN
const arr = [undefined, null, "", 0, false, NaN, 1, 2].filter(Boolean);
// arr => [1, 2]
30、在数组开头插入成员
let arr = [1, 2];
arr.unshift(0);
arr = [0].concat(arr);
arr = [0, ...arr];
// arr => [0, 1, 2]
31、在数组末尾插入元素
let arr = [0, 1];
arr.push(2);
arr.concat(2);
arr[arr.length] = 2;
arr = [...arr, 2];
// arr => [0, 1, 2]
32、计算数组成员的数量
const arr = [0, 1, 1, 2, 2, 2];
const count = arr.reduce((t, v) => {
t[v] = t[v] ? ++t[v] : 1;
return t;
}, {});
// count => { 0: 1, 1: 2, 2: 3 }
33、解构嵌套数组成员
const arr = [0, 1, [2, 3, [4, 5]]];
const [a, b, [c, d, [e, f]]] = arr;
// a b c d e f => 0 1 2 3 4 5
34、解构数组成员别名
const arr = [0, 1, 2];
const { 0: a, 1: b, 2: c } = arr;
// a b c => 0 1 2
35、解构数组成员默认值
const arr = [0, 1, 2];
const [a, b, c = 3, d = 4] = arr;
// a b c d => 0 1 2 4
36、获取随机数组成员
const arr = [0, 1, 2, 3, 4, 5];
const randomItem = arr[Math.floor(Math.random() * arr.length)];
// randomItem => 1
37、创建指定长度的数组
const arr = [...new Array(3).keys()];
// arr => [0, 1, 2]
38、创建一个指定长度和相等值的数组
const arr = new Array(3).fill(0);
// arr => [0, 0, 0]
39、数组内所有数字求和
const myArray = [10, 20, 30, 40];
const reducer = (total, currentValue) => total + currentValue;
console.log(myArray.reduce(reducer)); // 100
对象技能
39、克隆对象
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 }
40、合并对象
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 }
41、对象变量属性
const flag = false;
const obj = {
a: 0,
b: 1,
[flag ? "c" : "d"]: 2
};
// obj => { a: 0, b: 1, d: 2 }
42、创建一个纯空对象
const obj = Object.create(null);
Object.prototype.a = 0;
// obj => {}
43、删除对象无用属性
const obj = { a: 0, b: 1, c: 2 };
const { a, ...rest } = obj;
// rest => { b: 1, c: 2 }
44、解构对象属性嵌套
const obj = { a: 0, b: 1, c: { d: 2, e: 3 } };
const { c: { d, e } } = obj;
// d e => 2 3
45、解构对象属性别名
const obj = { a: 0, b: 1, c: 2 };
const { a, b: d, c: e } = obj;
// a d e => 0 1 2
46、解构对象属性默认值
const obj = { a: 0, b: 1, c: 2 };
const { a, b = 2, d = 3 } = obj;
// a b d => 0 1 3
函数技能
47、函数自执行
const Func = function() {}(); // Commonly used
(function() {})(); // Commonly used
(function() {}()); // Commonly used
[function() {}()];
+ function() {}();
- function() {}();
~ function() {}();
! function() {}();
new function() {};
new function() {}();
void function() {}();
typeof function() {}();
delete function() {}();
1, function() {}();
1 ^ function() {}();
1 > function() {}();
48、一次性函数
适合运行一些只需要执行一次的初始化代码。
function Func() {
console.log("x");
Func = function() {
console.log("y");
}
}
49、延迟加载函数
当函数中的复杂判断分支越来越多时,可以大大节省资源开销。
function Func() {
if (a === b) {
console.log("x");
} else {
console.log("y");
}
}
// replace with
function Func() {
if (a === b) {
Func = function() {
console.log("x");
}
} else {
Func = function() {
console.log("y");
}
}
return Func();
}
50、检测非空参数
function IsRequired() {
throw new Error("param is required");
}
function Func(name = IsRequired()) {
console.log("I Love " + name);
}
Func(); // "param is required"
Func("You"); // "I Love You"
51、字符串创建函数
const Func = new Function("name", "console.log(\"I Love \" + name)");
52、优雅地处理错误信息
try {
Func();
} catch (e) {
location.href = "https://stackoverflow.com/search?q=[js]+" + e.message;
}
53、优雅地处理 Async/Await 参数
function AsyncTo(promise) {
return promise.then(data => [null, data]).catch(err => [err]);
}
const [err, res] = await AsyncTo(Func());
54、优雅地处理多个函数返回值
function Func() {
return Promise.all([
fetch("/user"),
fetch("/comment")
]);
}
const [user, comment] = await Func();
DOM 技能
55、显示所有 DOM 边框
[].forEach.call($$("*"), dom => {
dom.style.outline = "1px solid #" + (~~(Math.random() * (1 << 24))).toString(16);
});
56、响应式页面
页面基于设计图但需要适配多个模型,元素大小使用rem设置。
function AutoResponse(width = 750) {
const target = document.documentElement;
target.clientWidth >= 600
? (target.style.fontSize = "80px")
: (target.style.fontSize = target.clientWidth / width * 100 + "px");
}
57、过滤 XSS
function FilterXss(content) {
let elem = document.createElement("div");
elem.innerText = content;
const result = elem.innerHTML;
elem = null;
return result;
}
58、访问本地存储
const love = JSON.parse(localStorage.getItem("love"));
localStorage.setItem("love", JSON.stringify("I Love You"));
其他技能
59、简写条件判断语句
如果仅在判断条件为 true 时才执行函数,则可以使用 && 简写
// 普通写法
if (condition) {doSomething();
}
// 简写
condition && doSomething();
60、多个或的条件判断语句
使用includes
const myTech = 'JavaScript';
const techs = ['html', 'css', 'JavaScript'];
// 普通写法
if (myTech === 'HTML' || myTech === 'CSS' || myTech === 'JavaScript') {
// do something
}
// includes 写法
if (techs.includes(myTech)) {
// do something
}
JS项目开发中常用的一些小功能相关推荐
- 项目开发中常用JS表单取值方法
项目开发中常用JS表单取值方法 一.常用表单基本取值方法(form1为表单名称,TextBox1为控件ID,以文本框为例,html控件与web服务器控件是一样的) 1.form1.Te ...
- Git码云项目开发中常用分支
Git码云项目开发中常用分支 master分支,即主分支.任何项目都必须有个这个分支.对项目进行tag或发布版本等操作,都必须在该分支上进行. develop分支,即开发分支,从master分支上检出 ...
- 项目开发中常用的git套路
在项目开发中常用的git套路: 1.在本地文件夹中,(在库名文件夹下)打开git bash 2.如果想在github上新建一个仓库,则 git init 否则略过这一步 3.建立关联 git re ...
- J2EE项目开发中常用到的公共方法
在项目IDCM中涉及到多种工单,包括有:服务器|网络设备上下架工单.服务器|网络设备重启工单.服务器光纤网线更换工单.网络设备撤线布线工单.服务器|网络设备替换工单.服务器|网络设备RMA工单.通用原 ...
- php项目开发中常用的助手函数
在日常开发中有很多小功能或者函数方法都是复用率极高的,整理成一个助手函数类. <?php /** *助手函数类 */ class Helper {/***密码加密*/public static ...
- 开发项目时mysql常用语句_项目开发中常用到的SQL语句
1.循环示例 循环示例代码: DECLARE @i intDECLARE 10 ) 10 ) 10001200 BEGINSet 110 )), 4 ) @name select @name Loco ...
- php页面开发,PHP网站开发中常用的8个小技巧
这篇文章主要介绍了PHP网站开发中常用的8个小技巧,本文讲解了命名.使用.PHP判断Form表单是否提交.PHP 获取字符串长度.PHP超全局对象等内容,需要的朋友可以参考下 PHP是一种用于创建动态 ...
- JS lodash库在开发中常用到的方法
目录 一.摘要 二.常用方法 一.摘要 lodash是JS一个开箱即用的库函数,里面对于在日常开发中常用到的方法都是已经封装好的,使用起来非常方便,本篇记录了在日常开发过程总经常用的方法,就大概记录一 ...
- jsp/html开发中常用的JS代码和页面特效代码
1.jsp/html开发中常用的JS代码 1.后退 前进 <input type="button" value="后退" onClick="hi ...
最新文章
- js用.和[]获取属性的区别
- 从 Dropdown 的 React 实现中学习到的
- 阿諾爾德的「常微分方程」中對「單參變換羣」的定義好像有問題
- 六、Mysql体系架构、存储引擎、临时表
- 简明python教程-Python简明入门教程
- java全局变量和局部变量_Java 10:局部变量类型推断
- [摘文]BizTalk概述
- BZOJ 1715: [Usaco2006 Dec]Wormholes 虫洞
- 方差分析 Analysis of Variance ANOVA 变异数分析 F检验
- linux像win7,如何使Ubuntu看起来像Windows 7
- 电影中的计算机 过去与未来
- 使用shell脚本实现everthing的功能
- 555定时器组成的应用之流水灯
- 数据库表的关联关系, 一对一, 一对零或一, 多对多
- pixel bender 学习备忘录
- tensorflow中的shape函数理解
- 美国大学英语写作第9版_笔记1_概况
- 写一个简单的python调用接口(API)
- webapi Filter
- 安徽省计算机学校排名,2018“中国最好学科排名”公布 安徽这14所高校上榜
热门文章
- JavaScript获取焦点并将光标移动到末尾字符
- 网络安全——传输层安全
- Ubuntu18.04安装wps office2016
- 8款Windows7专用免费杀毒软件(英文版)推荐
- java中集群和分布式的区别_java 分布式与集群的区别和联系
- SQL Server 2008转换成sql 2000数据库
- Wise Owl Says… by Brian O'Kane
- 解决 fatal error: third_party/lss/linux_syscall_support.h: 没有那个文件或目录
- HTML5期末大作业:节日网站设计——圣诞节(5页面)带背景+音乐+带视频+带登录HTML+CSS+JavaScript...
- 漏洞、bug、错误代码区别