菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
0
0

20个超级有用的 JavaScript 技巧

原创
05/13 14:22
阅读数 145

今天,我整理了20个很实用的 JavaScript 开发技巧,希望这些技巧能够帮助你的学习与开发工作。

1. 初始化一个数组

如果你想初始化一个指定长度的一维数组并指定默认值,你可以这样做。

const array = Array(6).fill(''); 
// ['', '', '', '', '', '']

如果你想初始化一个指定长度的二维数组并指定默认值,你可以这样做。

const matrix = Array(6).fill(0).map(() => Array(5).fill(0)); 
// [[0, 0, 0, 0, 0],
//  [0, 0, 0, 0, 0],
//  [0, 0, 0, 0, 0],
//  [0, 0, 0, 0, 0],
//  [0, 0, 0, 0, 0],
//  [0, 0, 0, 0, 0]]

2. 数组求和,求最大值和最小值

const array  = [5,4,7,8,9,2];

求和

array.reduce((a,b) => a+b);

寻找最大值

array.reduce((a,b) => a > b ? a : b);  Math.max(...array)

寻找最小值

array.reduce((a,b) => a < b ? a : b);  Math.min(...array)

请记住:数组的reduce方法可以用来解决很多数组求值问题。

3.过滤错误值

如果要过滤数组中的值,例如 false、0、null、undefined 等,可以这样做。

const array = [1, 0, undefined, 6, 7, '', false];
array.filter(Boolean);
// [1, 6, 7]

4. 使用逻辑运算符

如果有这样的代码片段:

if(a > 10) {
    doSomething(a)
}

可以使用逻辑运算符重写。

a > 10 && doSomething(a)

5. 简化判断

如果有如下判断。

if(a === undefined || a === 10 || a=== 15 || a === null) {
    //...
}

可以使用数组来简化这种判断。

if([undefined, 10, 15, null].includes(a)) {
    //...
}

这段代码会简洁很多,易于扩展,如果还需要再添加判断,直接添加到数组中即可。

6.空数组

如果要清空数组,可以将数组的长度设置为 0。

let array = ["A", "B", "C", "D", "E", "F"]
array.length = 0 
console.log(array)  // []

7. 计算性能

以下操作可用于计算代码的性能。

const startTime = performance.now(); 
for(let i = 0; i < 1000; i++) {
    console.log(i)
}
const endTime = performance.now();
const totaltime = endTime - startTime;
console.log(totaltime); // 10.3333333

8. 拼接阵列

如果我们想组合几个数组,我们可以使用扩展运算符。

const start = [1, 2] 
const end = [5, 6, 7] 
const numbers = [9, ...start, ...end, 8] // [9, 1, 2, 5, 6, 7 , 8]

或者使用数组的 concat()方法。

const start = [1, 2, 3, 4] 
const end = [5, 6, 7] 
start.concat(end); // [1, 2, 3, 4, 5, 6, 7]

但是,在使用concat()方法时,如果要合并的数组很大,那么,concat()函数在创建单独的新数组时会消耗大量内存。在这种情况下,可以使用以下方法来合并数组。

Array.prototype.push.apply(start, end)

9. 验证 undefined 和 null

如果有这样的代码。

if(a === null || a === undefined) {
    doSomething()
}

也就是如果需要验证一个值是否等于null或者undefined,可以使用null合并操作符来简化上面的代码。

a ?? doSomething()

这样,仅当 a 未定义或为空时,才会执行控制合并运算符之后的代码。空合并运算符 ??是一个逻辑运算符,当左侧操作数为 null 或未定义时返回其右侧操作数,否则返回左侧操作数。

10. 将数组元素转换为数字

如果有一个数组,并且你想将数组的元素转换为数字,你可以使用 map 方法来完成。

const array = ['12', '1', '3.1415', '-10.01'];
array.map(Number);  // [12, 1, 3.1415, -10.01]

这样,map 对数组的每个元素执行 Number 构造函数,并在遍历数组时返回结果。

11、将类数组转换为数组

可以使用以下方法将类数组转换为数组。

Array.prototype.slice.call(arguments);

此外,还可以使用扩展运算符来实现。

[...arguments]

12.对象属性的动态声明

如果你想动态地为一个对象声明属性,你可以这样做。

const dynamic = 'color';
var item = {
    brand: 'Ford',
    [dynamic]: 'Blue'
}
console.log(item); 
// { brand: "Ford", color: "Blue" }

13.缩短console.log()

每次debug都要写很多console.log()会比较麻烦,可以用下面的形式来简化这段代码。

const c = console.log.bind(document) 
c(222) 
c("hello world")

这将每次只执行 c 方法。

14.获取查询参数

如果我们想获取 URL 中的参数,可以使用 window 对象的属性。

window.location.search

如果一个 URL 是 google.com?project=js&type=1 那么通过上面的操作你会得到 ?project=js&type=1。如果你想得到其中一个参数,你可以这样做。

let type = new URLSearchParams(location.search).get('type');

15. 删除数组元素

如果我们想删除一个数组的元素,可以使用delete来完成,但是删除后元素会变成undefined,不会消失,而且执行会消耗很多时间,所以大部分情况下不会满足我们的需求。所以我们可以使用数组的 slice() 方法来删除数组的元素。

const array = ["a", "b", "c", "d"] 
array.splice(0, 2) // ["a", "b"]

16.检查对象是否为空

如果我们想检查对象是否为空,我们可以使用以下内容。

Object.keys({}).length  // 0
Object.keys({key: 1}).length  // 1

Object.keys() 方法用于获取对象的键,它将返回一个包含这些键值的数组。如果返回数组的长度为 0,则该对象必须为空。

17. 使用 switch case 替换 if/else

switch case 的性能比 if/else 好,而且代码看起来更干净。

前:

if (1 == month) {days = 31;}
else if (2 == month) {days = IsLeapYear(year) ? 29 : 28;}
else if (3 == month) {days = 31;}
else if (4 == month) {days = 30;} 
else if (5 == month) {days = 31;} 
else if (6 == month) {days = 30;} 
else if (7 == month) {days = 31;} 
else if (8 == month) {days = 31;} 
else if (9 == month) {days = 30;} 
else if (10 == month) {days = 31;} 
else if (11 == month) {days = 30;} 
else if (12 == month) {days = 31;}

后:

switch(month) {
        case 1: days = 31; break;
        case 2: days = IsLeapYear(year) ? 29 : 28; break;
        case 3: days = 31; break;
        case 4: days = 30; break;
        case 5: days = 31; break;
        case 6: days = 30; break;
        case 7: days = 31; break;
        case 8: days = 31; break;
        case 9: days = 30; break;
        case 10: days = 31; break;
        case 11: days = 30; break;
        case 12: days = 31; break;
        default: break;
}

18. 获取数组中的最后一项

如果要获取数组中的最后一项,通常会这样编写代码。

const arr = [1, 2, 3, 4, 5];
arr[arr.length - 1]  // 5

其实,我们也可以使用数组的 slice 方法来获取最后一个元素。

arr.slice(-1)

当我们将 slice 方法的参数设置为负值时,它会从数组后面开始截取数组值,如果要截取最后两个值,则传入参数-2。

19. 将值转换为布尔值

在 JavaScript 中,以下所有值在布尔转换时都转换为 false,所有其他值都转换为 true。
● undefined
● null
● 0
● -0
● NaN
● “”

通常,如果我们想将显式值转换为布尔值,我们会使用 Boolean() 方法进行转换。实际上,我们可以使用 !运算符将值转换为布尔值。

我们知道一个!是将对象转换为布尔值并反转它,两个!就是再次将逆布尔值取反,相当于直接将非布尔值转换为布尔值。与 Boolean() 方法相比,此操作将具有更快的性能,因为它是本机计算机操作:

!!undefined // false
!!"996"     // true
!!null      // false
!!NaN       // false

20. 使用对象代替参数列表

当我们使用参数列表给函数传递参数的时候,参数少一点没问题,但如果参数多,问题就更大了,因为我们必须按照参数列表的顺序传递参数。如果你使用 TypeScript 编写,那么你还需要编写使可选参数列在强制参数之后。

如果我们的函数参数比较多,可以考虑使用对象形式传参。以对象形式传递参数时,传递可选参数不需要在最后,参数的顺序也不重要。它也比参数列表更容易阅读和理解通过对象传递的内容。

请参阅下面的示例。

function getItem(price, quantity, name, description) {}
getItem(15, undefined, 'bananas', 'fruit')

以下是如何使用对象传递。

function getItem(args) {
    const {price, quantity, name, description} = args
}
getItem({
    name: 'bananas',
    price: 10,
    quantity: 1, 
    description: 'fruit'
})

总结

以上就是我今天跟你分享的20个JavaScript的实用技巧,希望这些技巧对你有所帮助。

发表评论

0/200
0 点赞
0 评论
收藏