关于javascript:11-个对开发有帮助的-JS-技巧进收藏夹当小词典吧

1次阅读

共计 2908 个字符,预计需要花费 8 分钟才能阅读完成。

作者:Orkhan Jafarov
译者:前端小智
起源: dev

点赞再看 ,微信搜寻【大迁世界】,B 站关注【前端小智】 这个没有大厂背景,但有着一股向上踊跃心态人。本文 GitHub https://github.com/qq44924588… 上曾经收录,文章的已分类,也整顿了很多我的文档,和教程材料。

最近开源了一个 Vue 组件,还不够欠缺,欢送大家来一起欠缺它,也心愿大家能给个 star 反对一下,谢谢各位了。

github 地址:https://github.com/qq44924588…

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. 转换十六进制→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'}

我是小智,我要去刷碗了,咱们下期见~


代码部署后可能存在的 BUG 没法实时晓得,预先为了解决这些 BUG,花了大量的工夫进行 log 调试,这边顺便给大家举荐一个好用的 BUG 监控工具 Fundebug。

原文:https://dev.to/11-javascript-…

交换

文章每周继续更新,能够微信搜寻「大迁世界」第一工夫浏览和催更(比博客早一到两篇哟),本文 GitHub https://github.com/qq449245884/xiaozhi 曾经收录,整顿了很多我的文档,欢送 Star 和欠缺,大家面试能够参照考点温习,另外关注公众号,后盾回复 福利,即可看到福利,你懂的。

正文完
 0