温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

对开发有帮助的JS技巧有哪些

发布时间:2021-10-18 17:48:09 来源:亿速云 阅读:74 作者:iii 栏目:web开发

这篇文章主要介绍“对开发有帮助的JS技巧有哪些”,在日常操作中,相信很多人在对开发有帮助的JS技巧有哪些问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”对开发有帮助的JS技巧有哪些”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

1. 生成一个带有随机数的列表

Array.from({ length: 1000 }, Math.random) // [ 0.6163093133259432, 0.8877401276499153, 0.4094354756035987, ...] - 1000 items

2.生成一个带有数字的列表

Array.from({ length: 1000 }, (v, i) => i) // [0, 1, 2, 3, 4, 5, 6....999]

3. RGB→转换为十六进制

const rgb2hex = ([r, g, b]) =>   `#${(1 << 24) + (r << 16) + (g << 8) + b}`.toString(16).substr(1);  rgb2hex([76, 11, 181]); // #4c0bb5

4. 转换十六进制&rarr;RGB

怎么把它转换回去?这是实现该目标的一种好方法。

const hex2rgb = hex =>   [1, 3, 5].map((h) => parseInt(hex.substring(h, h + 2), 16));  hex2rgb("#4c0bb5"); // [76, 11, 181]

5.奇数或偶数

使用 位 运算的方式:

const value = 232;    if (value & 1) console.log("odd"); else console.log("even"); // even

6.检查有效的 URL

const isValidURL = (url) => {   try {     new URL(url);     return true;   } catch (error) {     return false;   } }  isValidURL('https://segmentfault.com/u/minnanitkong/articles') // true  isValidURL("https//invalidto"); // false

7.距离过去到现在时间表示

有时我们需要打印6分钟前的日期,但不希望很大的库来完成。这里有一个小片段可以做到这一点:

const fromAgo = (date) => {   const ms = Date.now() - date.getTime();   const seconds = Math.round(ms / 1000);   const minutes = Math.round(ms / 60000);   const hours = Math.round(ms / 3600000);   const days = Math.round(ms / 86400000);   const months = Math.round(ms / 2592000000);   const years = Math.round(ms / 31104000000);    switch (true) {     case seconds < 60:       return `${seconds} second(s) ago"`;     case minutes < 60:       return `${minutes} minute(s) ago"`;     case hours < 24:       return `${hours} hour(s) ago"`;     case days < 30:       return `${days} day(s) ago`;     case months < 12:       return `${months} month(s) ago`;     default:       return `${years} year(s) ago`;   } };  const createdAt = new Date(2021, 0, 5); fromAgo(createdAt); // 14 day(s) ago;

8. 用参数生成路径

我们在处理路线/路径时常做很多工作,我们总是需要对其进行操作。当我们需要生成带有参数的路径以将浏览器推送到那里时,generatePath  可以帮助我们!

const generatePath = (path, obj) =>     path.replace(/(:[a-z]+)/g, (v) => obj[v.substr(1)]);  const route = "/app/:page/:id"; generatePath(route, {   page: "products",   id: 85, }); // /app/products/123

9.从路径获取参数

const getPathParams = (path, pathMap, serializer) => {   path = path.split("/");   pathMap = pathMap.split("/");   return pathMap.reduce((acc, crr, i) => {     if (crr[0] === ":") {       const param = crr.substr(1);       acc[param] = serializer && serializer[param]         ? serializer[param](path[i])         : path[i];     }     return acc;   }, {}); };  getPathParams("/app/products/123", "/app/:page/:id"); // { page: 'products', id: '123' }  getPathParams("/items/2/id/8583212", "/items/:category/id/:id", {   category: v => ['Car', 'Mobile', 'Home'][v],   id: v => +v }); // { category: 'Home', id: 8583212 }

10.用查询字符串生成路径

const getQueryParams = url =>   url.match(/([^?=&]+)(=([^&]*))/g).reduce((total, crr) => {     const [key, value] = crr.split("=");     total[key] = value;     return total;   }, {});  getQueryParams("/user?name=Orkhan&age=30"); // { name: 'Orkhan', age: '30' }

到此,关于“对开发有帮助的JS技巧有哪些”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js
AI