

15 elegant and simple JS one-line codes to make your work more efficient with half the effort!
JavaScript 非常大的特点容易上手且非常灵活,代码实现方式五花八门;有时候能一行代码解决,就尽量不用两行。
本文整理了非常有用的单行代码,这些需求都是在开发中非常常见的,用单行代码可以帮助你提高工作效率。
数组去重
从数组中删除所有重复值,实现方式非常多,我们这里就说最简单的方式,一行代码搞定:
const uniqueArr = (arr) => [...new Set(arr)]; console.log(uniqueArr(["前端","js","html","js","css","html"])); // ['前端', 'js', 'html', 'css']
uniqueArr
方法将数据转为Set,然后再解构为数组返回。
从url获取参数并转为对象
网页路径经常是:www.baidu.com?search=js&xxx=kkk
这种形式的,我们是经常需要取参数的,可以使用第三方的qs
包实现,如果你只是要实现去参数,这一句代码就可以实现,不用再引入qs
了。
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'}
检查对象是否为空
检查对象是否为空,实际上并不那么简单,即使对象为空,每次检查对象是否等于 {}
也会返回 false
。
幸运的是,下面的单行代码正是我们想要的。
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object; isEmpty({}) // true isEmpty({a:"not empty"}) //false
反转字符串
反转字符串可以使用split
结合reverse
和join
方法轻松实现。
const reverse = str => str.split('').reverse().join(''); reverse('this is reverse'); // esrever si siht
生成随机十六进制
生成随机数相信你能信手拈来,那随机生成十六进制,例如生成十六进制颜色值。
const randomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}` console.log(randomHexColor()); // #a2ce5b
检查当前选项卡是否在后台
浏览器使用选项卡式浏览,任何网页都有可能在后台,此时对用户来说是没有在浏览的, 知道怎么快速检测到,你的网页对用户是隐藏还是可见吗?
const isTabActive = () => !document.hidden; isTabActive() // true|false
检测元素是否处于焦点
activeElement
属性返回文档中当前获得焦点的元素。
const elementIsInFocus = (el) => (el === document.activeElement); elementIsInFocus(anyElement) // 元素处于焦点返回true,反之返回false
检查设备类型
使用navigator.userAgent
判断是移动设备还是电脑设备:
const judgeDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'PC'; judgeDeviceType() // PC | Mobile
文字复制到剪贴板
Clipboard API
它的所有操作都是异步的,返回 Promise
对象,不会造成页面卡顿。而且,它可以将任意内容(比如图片)放入剪贴板。
const copyText = async (text) => await navigator.clipboard.writeText(text) copyText('单行代码 前端世界')
获取选定的文本
使用内置的 getSelection
获取用户选择的文本:
const getSelectedText = () => window.getSelection().toString(); getSelectedText(); // 返回选中的内容
查询某天是否为工作日
我们自己写日历组件时经常会用到,判断某个日期是否为工作日;周一至周五为工作日:
const isWeekday = (date) => date.getDay() % 6 !== 0; isWeekday(new Date(2022, 03, 11)) // true
转换华氏/摄氏
处理温度有时会晕头转向。这两个函数则能帮助大家将华氏温度转换为摄氏温度,以及将摄氏温度转换为华氏温度。
- 将华氏温度转换为摄氏温度
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9; fahrenheitToCelsius(50); // 10
- 将摄氏温度转华氏温度
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32; celsiusToFahrenheit(100) // 212
两日期之间相差的天数
日常开发中经常遇到需要显示剩余天数, 一般我们就需要计算两日期之间相差天数:
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
将 RGB 转换为十六进制
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
原文地址:https://juejin.cn/post/7145623660680708104

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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 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

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 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 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

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).

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

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