Table of Contents
数组去重
从url获取参数并转为对象
检查对象是否为空
反转字符串
生成随机十六进制
检查当前选项卡是否在后台
检测元素是否处于焦点
检查设备类型
文字复制到剪贴板
获取选定的文本
查询某天是否为工作日
转换华氏/摄氏
两日期之间相差的天数
将 RGB 转换为十六进制
计算数组平均值
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!

Oct 12, 2022 pm 07:17 PM
javascript

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 id="strong-计算数组平均值-strong"><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前端开发编程基础视频

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service