Home>Article>Web Front-end> Learn these 20+ JavaScript one-liners to help you code like a pro
This article introduces you to 20 JavaScript one-liners that can help you write code like a professional. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
JavaScript continues to grow and develop,
because it is one of the easiest languages to get started with, and therefore new to the marketbecomes a tech geek
Opened the door. (Question mark face?)
Indeed, JavaScript can do many wonderful things! There is still much to learn.
And, whether you're new to JavaScript or more of a professional developer, learning something new is always a good thing.
This article has compiled some very useful one-liners (20) that can help you improve your work efficiency and help debug your code.
What is a single line of code?
One-liner is a coding practice in which we perform certain functions with only one line of code.
This function will return a Boolean value (true or false) using theMath.random()
method.Math.random
Create a random number between 0 and 1, then we check if it is greater or less than 0.5.
This means there is a 50/50 chance of getting it right or wrong.
const getRandomBoolean = () => Math.random() >= 0.5; console.log(getRandomBoolean()); // a 50/50 chance of returning true or false
With this feature you will be able to check if the provided date is a weekday or a weekend.
const isWeekend = (date) => [0, 6].indexOf(date.getDay()) !== -1; console.log(isWeekend(new Date(2021, 4, 14))); // false (Friday) console.log(isWeekend(new Date(2021, 4, 15))); // true (Saturday)
Simple utility function to check if a number is even or odd.
const isEven = (num) => num % 2 === 0; console.log(isEven(5)); // false console.log(isEven(4)); // true
Very simple way to remove all duplicate values from an array . This function converts an array to a Set and then returns an array.
const uniqueArr = (arr) => [...new Set(arr)]; console.log(uniqueArr([1, 2, 3, 1, 2, 3, 4, 5])); // [1, 2, 3, 4, 5]
A clean and easy way to check if a variable is an array.
Of course, there can also be other methods
const isArray = (arr) => Array.isArray(arr); console.log(isArray([1, 2, 3])); // true console.log(isArray({ name: 'Ovi' })); // false console.log(isArray('Hello World')); // false
This will take two numbers as arguments and will generate a random number between those two numbers!
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min); console.log(random(1, 50)); // could be anything from 1 - 50
Maybe you need atemporary
unique ID, here is a trick you can use on the go Generate a random string.
const randomString = () => Math.random().toString(36).slice(2); console.log(randomString()); // could be anything!!!
Thewindow.scrollTo()
method puts aThe X
andY
coordinates scroll to.
If we set them to zero and zero, we will scroll to the top of the page.
const scrollToTop = () => window.scrollTo(0, 0); scrollToTop();
Switching Boolean values is one of the very basic programming problems that can be solved in many different ways.
Instead of using an if statement to determine which value to set the boolean to, you can use a function! Flip the current value.non-
operator.
// bool is stored somewhere in the upperscope const toggleBool = () => (bool = !bool); //or const toggleBool = b => !b;
The code below is to swap two variables without using the third variable and using only one line of code One of the simpler ways to use a variable.
[foo, bar] = [bar, foo];
To calculate the number of days between two dates,
we first Find the absolute value between the two dates, then divide it by 86400000 (equal to the number of milliseconds in a day), and finally round the result and return it.
const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000); console.log(daysDiff(new Date('2021-05-10'), new Date('2021-11-25'))); // 199
PS: You may need to add a check to see ifnavigator.clipboard exists .writeText
const copyTextToClipboard = async (text) => { await navigator.clipboard.writeText(text); };
There are two ways to merge arrays. One of them is to use theconcat
method. The other uses the spread operator (…
).
PS: We can also use the "settings" object to copy anything from the final array.
// Merge but don't remove the duplications const merge = (a, b) => a.concat(b); // Or const merge = (a, b) => [...a, ...b]; // Merge and remove the duplications const merge = [...new Set(a.concat(b))]; // Or const merge = [...new Set([...a, ...b])];
人们有时会使用库来查找JavaScript中某些内容的实际类型,这一小技巧可以节省你的时间(和代码大小)。
const trueTypeOf = (obj) => { return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase(); }; console.log(trueTypeOf('')); // string console.log(trueTypeOf(0)); // number console.log(trueTypeOf()); // undefined console.log(trueTypeOf(null)); // null console.log(trueTypeOf({})); // object console.log(trueTypeOf([])); // array console.log(trueTypeOf(0)); // number console.log(trueTypeOf(() => {})); // function
需要从头开始截断字符串,这不是问题!
const truncateString = (string, length) => { return string.length < length ? string : `${string.slice(0, length - 3)}...`; }; console.log( truncateString('Hi, I should be truncated because I am too loooong!', 36), ); // Hi, I should be truncated because...
从中间截断字符串怎么样?
该函数将一个字符串作为第一个参数,然后将我们需要的字符串大小作为第二个参数,然后从第3个和第4个参数开始和结束需要多少个字符
const truncateStringMiddle = (string, length, start, end) => { return `${string.slice(0, start)}...${string.slice(string.length - end)}`; }; console.log( truncateStringMiddle( 'A long story goes here but then eventually ends!', // string 25, // 需要的字符串大小 13, // 从原始字符串第几位开始截取 17, // 从原始字符串第几位停止截取 ), ); // A long story ... eventually ends!
好吧,不幸的是,JavaScript
没有内置函数来大写字符串,但是这种解决方法可以实现。
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1); console.log(capitalize('hello world')); // Hello world
此简单的帮助程序方法根据选项卡是否处于视图/焦点状态而返回true
或false
const isTabInView = () => !document.hidden; // Not hidden isTabInView(); // true/false
如果用户使用的是Apple
设备,则返回true
const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform); console.log(isAppleDevice); // true/false
当你只想在一行中编写if..else
语句时,这是一个很好的代码保护程序。
// Longhand const age = 18; let greetings; if (age < 18) { greetings = 'You are not old enough'; } else { greetings = 'You are young!'; } // Shorthand const greetings = age < 18 ? 'You are not old enough' : 'You are young!';
在将变量值分配给另一个变量时,可能要确保源变量不为null,未定义或为空。
可以编写带有多个条件的long if语句,也可以使用短路评估。
// Longhand if (name !== null || name !== undefined || name !== '') { let fullName = name; } // Shorthand const fullName = name || 'buddy';
希望对你有所帮助!
英文原文地址:https://dev.to/ovi/20-javascript-one-liners-that-will-help-you-code-like-a-pro-4ddc
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of Learn these 20+ JavaScript one-liners to help you code like a pro. For more information, please follow other related articles on the PHP Chinese website!