原文:10 JavaScript Oneliners You Have Got to Add Your Arsenal as a Developer

封面:Photo by Charles Deluvio on Unsplash

1. 字符串首字母大写

使用此函数,你可以将字符串输入的首字母大写。其可以是一个单词,也可以是整个句子。

// Capitalize the first letter of a string
const capitalize = str => `${str.charAt(0).toUpperCase()}${str.slice(1)}`;

capitalize("hello, you are a cool person!");
// Result: "Hello, you are a cool person!"

2. 计算两个日期间隔天数

可能你需要了解, “1000 * 60 * 60 * 24” 是一天中的毫秒数。

// Calculate the number of days between two dates
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));

diffDays(new Date('2014-12-19'), new Date('2020-01-01'));
// Result: 1839

3. 转换字符串为数字

使用强制类型将字符串转换为数字的一种非常直接的方法。

// Convert a string to a number implicitly
toNumber = str => +str;

// Convert a string to a number explicitly
toNumber = str => Number(str);

toNumber("2");
// Result: 2

4. 检测数组是否包含元素

使用 ”isArray“ 方法以及检测数组长度是否大于 0,我们能检测是否其为空。

// Check if an array contains any items
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);
// Result: true

isNotEmpty([]);
// Result: false

5. 合并多个数组的不同方式

有很多合并数组的不同方式。其中之一是使用 ”concat“ 方法。另一种是使用扩展运算符 ("…")。

我们也可使用 “Set” 对象的方式来去重,

// Different ways of merging multiple arrays

// 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])];

6. 数字数组排序

JavaScript的内置排序(sort)方法比较棘手。它不能很好地处理数字,上述功能是对数组进行排序的一种简单方式。

// Sort an array containing numbers
const sort = arr => arr.sort((a, b) => a - b);

sort([1, 5, 2, 4, 3]);
// Result: [1, 2, 3, 4, 5]

7. 生成随机 HEX 颜色数值

生成 RGB 颜色相对比较简单,但产生一个随机的 HEX 颜色会有些复杂。

这个函数将使用生成一个随机的 HEX 颜色数值。

Generating an RGB color is a little more simple, but creating a random HEX color can get a little complex. This function will allow you to generate a random HEX color.

// Generate a random HEX color
randomColor = () => `#${Math.random().toString(16).slice(2, 8).padStart(6, '0')}`;

// Or
randomColor = () => `#${(~~(Math.random()*(1<<24))).toString(16)}`;

已知 cookie 名称想要读取它的具体值?

我们可取自 document 对象的属性值 ”cookie“ 并将其值返回给我们。

// Get the value of a specified cookie
cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();

cookie('_ga');
// Result: "GA1.2.1929736587.1601974046"

9. 交换两个变量的值

有时你只需要交换两个变量的值。这个简单的方式可让你用一行代码做到。

// Swap the values of 2 variables
let a = 1;
let b = 2;
[a, b] = [b, a];

// Result: 
// a = 2
// b = 1

10. 获取用户选中的文字

每当用户使用鼠标选择了文字,我们可以直接用 window 对象的 “getSelection” 方法来获取它。

// Get the text that the user has selected
const getSelectedText = () => window.getSelection().toString();

getSelectedText();