本篇文章给大家分享11 个对开发有帮助的 js 技巧。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
相关推荐:JavaScript视频教程
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]) => `#${(14. 转换十六进制→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')// trueisValidURL("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 seconds8. 用参数生成路径
我们在处理路线/路径时常做很多工作,我们总是需要对其进行操作。 当我们需要生成带有参数的路径以将浏览器推送到那里时,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' }登录后复制
原文地址:https://dev.to/11-javascript-tips-and-tricks-to-code-like-a-superhero-vol-2-mp6作者:Orkhan Jafarov译文地址:https://segmentfault.com/a/1190000039122988
更多编程相关知识,请访问:编程视频!!
以上就是值得收藏的11个对开发有帮助的 JS 技巧的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2717426.html