提升JS编程效率:19个实用JS代码示例

本文翻译自 19 Practical ES6 Snippets to Solve Common JS Problems,作者: Madza, 略有删改。

在实际工作中,开发者常面临一些需巧妙编程解决的挑战。有时几行代码就能迎刃而解。本文整理了一系列实用代码片段,助您轻松处理URL、DOM操作、事件处理、日期处理以及用户偏好设置等常见问题。

这些精选代码片段均源自"30 seconds of code"------一个卓越的编程资源库。我强烈推荐您查阅其完整代码,以获得更多灵感。

选择这些代码片段的首要准则是它们的实用性。希望您能在这里发现宝贵的资源,并将其应用于未来的项目中,以提升编程效率和质量。

1.如何获取base URL?

js 复制代码
const getBaseURL = url => url.replace(/[?#].*$/, '');

getBaseURL('http://url.com/page?name=Adam&surname=Smith');
// 'http://url.com/page'

2.如何检查URL是否是绝对的?

js 复制代码
const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);

isAbsoluteURL('https://google.com'); // true
isAbsoluteURL('ftp://www.myserver.net'); // true
isAbsoluteURL('/foo/bar'); // false

3.如何获取URL参数作为对象?

js 复制代码
const getURLParameters = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => (
      (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a
    ),
    {}
  );

getURLParameters('google.com'); // {}
getURLParameters('http://url.com/page?name=Adam&surname=Smith');
// {name: 'Adam', surname: 'Smith'}

4.如何检查一个元素是否包含另一个元素?

js 复制代码
const elementContains = (parent, child) =>
  parent !== child && parent.contains(child);

elementContains(
  document.querySelector('head'),
  document.querySelector('title')
);
// true
elementContains(document.querySelector('body'), document.querySelector('body'));
// false

5.如何获取元素的所有祖先?

js 复制代码
const getAncestors = el => {
  let ancestors = [];
  while (el) {
    ancestors.unshift(el);
    el = el.parentNode;
  }
  return ancestors;
};

getAncestors(document.querySelector('nav'));
// [document, html, body, header, nav]

6.如何将元素平滑滚动到视图中?

js 复制代码
const smoothScroll = element =>
  document.querySelector(element).scrollIntoView({
    behavior: 'smooth'
  });

smoothScroll('#fooBar'); // scrolls smoothly to the element with the id fooBar
smoothScroll('.fooBar');
// scrolls smoothly to the first element with a class of fooBar

7.如何处理元素外部的单击?

js 复制代码
const onClickOutside = (element, callback) => {
  document.addEventListener('click', e => {
    if (!element.contains(e.target)) callback();
  });
};

onClickOutside('#my-element', () => console.log('Hello'));
// Will log 'Hello' whenever the user clicks outside of #my-element

8.如何生成UUID?

js 复制代码
const UUIDGeneratorBrowser = () =>
  ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
    (
      c ^
      (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
    ).toString(16)
  );

UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d'

9.如何获取所选文本?

js 复制代码
const getSelectedText = () => window.getSelection().toString();

getSelectedText(); // 'Lorem ipsum'

10.如何将文本复制到剪贴板?

js 复制代码
const copyToClipboard = str => {
  if (navigator && navigator.clipboard && navigator.clipboard.writeText)
    return navigator.clipboard.writeText(str);
  return Promise.reject('The Clipboard API is not available.');
};

11.如何为HTML元素添加样式?

js 复制代码
const addStyles = (el, styles) => Object.assign(el.style, styles);

addStyles(document.getElementById('my-element'), {
  background: 'red',
  color: '#ffff00',
  fontSize: '3rem'
});

12.如何切换全屏模式?

js 复制代码
const fullscreen = (mode = true, el = 'body') =>
  mode
    ? document.querySelector(el).requestFullscreen()
    : document.exitFullscreen();

fullscreen(); // Opens `body` in fullscreen mode
fullscreen(false); // Exits fullscreen mode

13.如何检测Caps Lock是否打开?

html 复制代码
<form>
  <label for="username">Username:</label>
  <input id="username" name="username">

  <label for="password">Password:</label>
  <input id="password" name="password" type="password">
  <span id="password-message" style="display: none">Caps Lock is on</span>
</form>
js 复制代码
const el = document.getElementById('password');
const msg = document.getElementById('password-message');

el.addEventListener('keyup', e => {
  msg.style = e.getModifierState('CapsLock')
    ? 'display: block'
    : 'display: none';
});

14.如何检查日期是否有效?

js 复制代码
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

isDateValid('December 17, 1995 03:24:00'); // true
isDateValid('1995-12-17T03:24:00'); // true
isDateValid('1995-12-17 T03:24:00'); // false
isDateValid('Duck'); // false
isDateValid(1995, 11, 17); // true
isDateValid(1995, 11, 17, 'Duck'); // false
isDateValid({}); // false

15.如何从日期中获取时分秒信息?

js 复制代码
const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);

getColonTimeFromDate(new Date()); // '08:38:00'

16.如何从Date生成UNIX时间戳?

js 复制代码
const getTimestamp = (date = new Date()) => Math.floor(date.getTime() / 1000);

getTimestamp(); // 1602162242

17.如何查看当前用户的首选语言?

js 复制代码
const detectLanguage = (defaultLang = 'en-US') =>
  navigator.language ||
  (Array.isArray(navigator.languages) && navigator.languages[0]) ||
  defaultLang;

detectLanguage(); // 'nl-NL'

18.如何查看用户的首选配色方案?

js 复制代码
const prefersDarkColorScheme = () =>
  window &&
  window.matchMedia &&
  window.matchMedia('(prefers-color-scheme: dark)').matches;

prefersDarkColorScheme(); // true

19.如何检查设备是否支持触摸事件?

js 复制代码
const supportsTouchEvents = () =>
  window && 'ontouchstart' in window;

supportsTouchEvents(); // true

在这篇文章中,我们列举了一些精心挑选的代码片段来解决开发过程中的常见挑战。这些代码片段涵盖了处理URL、DOM操作、事件处理、日期处理和用户偏好设置等多个方面,旨在提供简洁而高效的解决方案。希望你能在日常工作中找到并应用这些有价值的代码片段,从而提升编程效率和质量。


看完本文如果觉得有用,记得点个赞支持,收藏起来说不定哪天就用上啦~

专注前端开发,分享前端相关技术干货,公众号:南城大前端(ID: nanchengfe)

相关推荐
浮华似水15 分钟前
简洁之道 - React Hook Form
前端
ok!ko2 小时前
设计模式之原型模式(通俗易懂--代码辅助理解【Java版】)
java·设计模式·原型模式
正小安2 小时前
如何在微信小程序中实现分包加载和预下载
前端·微信小程序·小程序
拉里小猪的迷弟3 小时前
设计模式-创建型-常用:单例模式、工厂模式、建造者模式
单例模式·设计模式·建造者模式·工厂模式
_.Switch4 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
一路向前的月光4 小时前
Vue2中的监听和计算属性的区别
前端·javascript·vue.js
长路 ㅤ   4 小时前
vite学习教程06、vite.config.js配置
前端·vite配置·端口设置·本地开发
长路 ㅤ   4 小时前
vue-live2d看板娘集成方案设计使用教程
前端·javascript·vue.js·live2d
Fan_web4 小时前
jQuery——事件委托
开发语言·前端·javascript·css·jquery
安冬的码畜日常4 小时前
【CSS in Depth 2 精译_044】第七章 响应式设计概述
前端·css·css3·html5·响应式设计·响应式