JavaScript 速记技巧
让我们来看看一些速记技巧和其他窍门。
请记住,其中一些是不可读的,并且可能看起来与项目使用无关,但我的目的是让您意识到这些技巧的存在。
为多个变量赋值
我们可以使用数组解构在一行中为多个变量赋值。
//Longhand
let a, b, c;
a = 5;
b = 8;
c = 12;
//Shorthand
let [a, b, c] = [5, 8, 12];
分配默认值
如果预期值为假,我们可以使用OR(||)
短路评估或空值合并运算符为变量分配默认值。(??)
//Longhand
let imagePath;
let path = getImagePath();
if (path !== null && path !== undefined && path !== '') {
imagePath = path;
} else {
imagePath = 'default.jpg';
}
//Shorthand
let imagePath = getImagePath() || 'default.jpg';
// OR
let imagePath = getImagePath() ?? 'default.jpg';
AND(&&) 短路评估
如果仅当变量为时才调用函数true
,那么您可以使用AND(&&)
短路作为替代方法。
//Longhand
if (isLoggedin) {
goToHomepage();
}
//Shorthand
isLoggedin && goToHomepage();
交换两个变量
要交换两个变量,我们通常使用第三个变量。我们可以通过数组解构赋值轻松地交换两个变量。
let x = 'Hello', y = 55;
//Longhand
const temp = x;
x = y;
y = temp;
//Shorthand
[x, y] = [y, x];
模板字符串
我们通常使用+
运算符将字符串值与变量连接起来。使用 ES6 模板字面量,我们可以用更简单的方式做到这一点。
//Longhand
console.log('You got a missed call from ' + number + ' at ' + time);
//Shorthand
console.log(`You got a missed call from ${number} at ${time}`);
多重条件检查
对于多个值匹配,我们可以将所有值放在一个数组中并使用indexOf()
或includes()
方法。
//Longhand
if (value === 1 || value === 'one' || value === 2 || value === 'two') {
// Execute some code
}
// Shorthand
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) {
// Execute some code
}
// OR
if ([1, 'one', 2, 'two'].includes(value)) {
// Execute some code
}
对象属性赋值
如果变量名和对象键名相同,那么我们可以在对象字面量中直接使用变量名,而不必同时使用键和值。JavaScript 会自动将键设置为变量名,并将值赋值为变量值。
let firstname = 'Amitav';
let lastname = 'Mishra';
//Longhand
let obj = {firstname: firstname, lastname: lastname};
//Shorthand
let obj = {firstname, lastname};
字符串转为数字
我们只需(+)
在字符串值前面提供一个一元运算符,就可以将字符串转换为数字。
//Longhand
let total = parseInt('453', 10);
let average = parseFloat('42.6', 10);
//Shorthand
let total = +'453';
let average = +'42.6';
指数幂
我们可以使用Math.pow()
方法来求一个数的幂。使用双星号 可以更简洁地实现此操作(**)
。
//Longhand
const power = Math.pow(4, 3); // 64
// Shorthand
const power = 4**3; // 64
双重非位运算符(~~)
双重非位运算符是方法的替代Math.floor()
。
//Longhand
const floor = Math.floor(6.8); // 6
// Shorthand
const floor = ~~6.8; // 6
双重非位运算符方法仅适用于 32 位整数,即 (2**31)-1 = 2147483647。因此,对于任何大于 2147483647 且小于 0 的数字,位运算符
(~~)
都会给出错误的结果,因此建议在这种情况下使用Math.floor()
。
查找数组中的最大值和最小值
const arr = [2, 8, 15, 4];
Math.max(...arr); // 15
Math.min(...arr); // 2
数组合并
let arr1 = [20, 30];
//Longhand
let arr2 = arr1.concat([60, 80]); // [20, 30, 60, 80]
//Shorthand
let arr2 = [...arr1, 60, 80]; // [20, 30, 60, 80]
从数组中删除错误值
let arr = [12, null, 0, 'xyz', null, -25, NaN, '', undefined, 0.5, false];
let filterArray = arr.filter(Boolean);
// filterArray = [12, "xyz", -25, 0.5]
注意:零 (0) 被视为假值,因此在两种情况下都会被移除。您可以添加额外的零值检查来保留它。
从数组中删除重复项
const arr = [10, 5, 20, 10, 6, 5, 8, 5, 20];
const unique = [...new Set(arr)];
console.log(unique); // [10, 5, 20, 6, 8]
创建随机字符串令牌
const token = Math.random().toString(36).slice(2);
// it will create a 11 character string. Ex: '3efstaz9g8a'
查找函数所需的参数数量
function func(a, b, c) {
// code
}
console.log(func.length); // 3
// function with Rest parameter
function func(a, b, ...c) {
// code
}
console.log(func.length); // 2
检查对象中是否存在某个键
const ob = {x: 5, y: 10};
// using "in" operator
console.log('x' in ob); // true
console.log('abc' in ob); // false
// using Reflect object
console.log(Reflect.has(ob, 'x')); // true
console.log(Reflect.has(ob, 'abc')); // false
您可能还喜欢
- JavaScript 中的映射以及何时使用它而不是对象
- JavaScript 设置对象来存储唯一值
- JavaScript 中的生成器函数
- Object.defineProperty() 方法简介
- JavaScript 中的振动 API
- JavaScript Fetch API 用于发出 HTTP 请求
- Object.freeze() 与 Object.seal() 与 Object.preventExtensions()
感谢您的时间❤️在jscurious.com
上查找我在 Web 开发博客上的更多文章