Home > headlines > 15 elegant and simple JS one-line codes to make your work more efficient with half the effort!

15 elegant and simple JS one-line codes to make your work more efficient with half the effort!

青灯夜游
Release: 2022-10-12 19:17:25
forward
3387 people have browsed it

JavaScript 非常大的特点容易上手且非常灵活,代码实现方式五花八门;有时候能一行代码解决,就尽量不用两行。

本文整理了非常有用的单行代码,这些需求都是在开发中非常常见的,用单行代码可以帮助你提高工作效率。

数组去重

从数组中删除所有重复值,实现方式非常多,我们这里就说最简单的方式,一行代码搞定:

15 elegant and simple JS one-line codes to make your work more efficient with half the effort!

const uniqueArr = (arr) => [...new Set(arr)];

console.log(uniqueArr(["前端","js","html","js","css","html"]));
// ['前端', 'js', 'html', 'css']
Copy after login

uniqueArr方法将数据转为Set,然后再解构为数组返回。

从url获取参数并转为对象

网页路径经常是:www.baidu.com?search=js&xxx=kkk这种形式的,我们是经常需要取参数的,可以使用第三方的qs包实现,如果你只是要实现去参数,这一句代码就可以实现,不用再引入qs了。

15 elegant and simple JS one-line codes to make your work more efficient with half the effort!

const getParameters = URL => JSON.parse(`{"${decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`
  )

getParameters("https://www.google.com.hk/search?q=js+md&newwindow=1");
// {q: 'js+md', newwindow: '1'}
Copy after login

检查对象是否为空

检查对象是否为空,实际上并不那么简单,即使对象为空,每次检查对象是否等于 {} 也会返回 false

幸运的是,下面的单行代码正是我们想要的。

15 elegant and simple JS one-line codes to make your work more efficient with half the effort!

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
isEmpty({}) // true
isEmpty({a:"not empty"}) //false
Copy after login

反转字符串

反转字符串可以使用split结合reversejoin方法轻松实现。

15 elegant and simple JS one-line codes to make your work more efficient with half the effort!

const reverse = str => str.split('').reverse().join('');
reverse('this is reverse');
// esrever si siht
Copy after login

生成随机十六进制

生成随机数相信你能信手拈来,那随机生成十六进制,例如生成十六进制颜色值。

15 elegant and simple JS one-line codes to make your work more efficient with half the effort!

const randomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`
console.log(randomHexColor());
// #a2ce5b
Copy after login

检查当前选项卡是否在后台

浏览器使用选项卡式浏览,任何网页都有可能在后台,此时对用户来说是没有在浏览的, 知道怎么快速检测到,你的网页对用户是隐藏还是可见吗?

15 elegant and simple JS one-line codes to make your work more efficient with half the effort!

const isTabActive = () => !document.hidden; 

isTabActive()
// true|false
Copy after login

检测元素是否处于焦点

activeElement 属性返回文档中当前获得焦点的元素。

15 elegant and simple JS one-line codes to make your work more efficient with half the effort!

const elementIsInFocus = (el) => (el === document.activeElement);

elementIsInFocus(anyElement)
// 元素处于焦点返回true,反之返回false
Copy after login

检查设备类型

使用navigator.userAgent 判断是移动设备还是电脑设备:

15 elegant and simple JS one-line codes to make your work more efficient with half the effort!

const judgeDeviceType =
      () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'PC';

judgeDeviceType()  // PC | Mobile
Copy after login

文字复制到剪贴板

Clipboard API 它的所有操作都是异步的,返回 Promise 对象,不会造成页面卡顿。而且,它可以将任意内容(比如图片)放入剪贴板。

15 elegant and simple JS one-line codes to make your work more efficient with half the effort!

const copyText = async (text) => await navigator.clipboard.writeText(text)
copyText('单行代码 前端世界')
Copy after login

获取选定的文本

使用内置的 getSelection 获取用户选择的文本:

15 elegant and simple JS one-line codes to make your work more efficient with half the effort!

const getSelectedText = () => window.getSelection().toString();

getSelectedText();
// 返回选中的内容
Copy after login

查询某天是否为工作日

我们自己写日历组件时经常会用到,判断某个日期是否为工作日;周一至周五为工作日:

115 elegant and simple JS one-line codes to make your work more efficient with half the effort!

const isWeekday = (date) => date.getDay() % 6 !== 0;

isWeekday(new Date(2022, 03, 11))
// true
Copy after login

转换华氏/摄氏

处理温度有时会晕头转向。这两个函数则能帮助大家将华氏温度转换为摄氏温度,以及将摄氏温度转换为华氏温度。

115 elegant and simple JS one-line codes to make your work more efficient with half the effort!

  • 将华氏温度转换为摄氏温度
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;

fahrenheitToCelsius(50);
// 10
Copy after login
  • 将摄氏温度转华氏温度
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;

celsiusToFahrenheit(100)
// 212
Copy after login

两日期之间相差的天数

日常开发中经常遇到需要显示剩余天数, 一般我们就需要计算两日期之间相差天数:

115 elegant and simple JS one-line codes to make your work more efficient with half the effort!

const dayDiff = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);

dayDiff(new Date("2021-10-21"), new Date("2022-02-12"))
// Result: 114
Copy after login

将 RGB 转换为十六进制

115 elegant and simple JS one-line codes to make your work more efficient with half the effort!

const rgbToHex = (r, g, b) =>   "#" + ((1 <h3 data-id="heading-14"><strong>计算数组平均值</strong></h3><p>计算平均值的方式很多,计算的逻辑都是一样的, 但是实现方式各不相同,一行代码简单实现:</p><p><img src="https://img.php.cn/upload/image/458/884/487/16655730787706515%20elegant%20and%20simple%20JS%20one-line%20codes%20to%20make%20your%20work%20more%20efficient%20with%20half%20the%20effort!" title="16655730787706515 elegant and simple JS one-line codes to make your work more efficient with half the effort!" alt="115 elegant and simple JS one-line codes to make your work more efficient with half the effort!"></p><pre class="brush:php;toolbar:false">const average = (arr) => arr.reduce((a, b) => a + b) / arr.length;
average([1,9,18,36]) //16
Copy after login

原文地址:https://juejin.cn/post/7145623660680708104

(学习视频分享:web前端开发编程基础视频

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template