20个JavaScript开发小技巧

2024年08月01日 建站教程

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)) {
    //...
}

这样代码就会简洁很多,并且便于扩展,如果还有需要等于a的判断,直接在数组中添加即可。

6. 清空数组

如果想要清空一个数组,可以将数组的length置于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); // 30.299999952316284

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.push.apply(start, end)

通过这种方式就能在很大程度上较少内存的使用。

9. 对象验证方式

如果我们有一个这样的对象:

const parent = {
    child: {
      child1: {
        child2: {
          key: 10
      }
    }
  }
}

很多时候我们会这样去写,避免某一层级不存在导致报错:

parent && parent.child && parent.child.child1 && parent.child.child1.child2

这样代码看起来就会很臃肿,可以使用JavaScript的可选链运算符:

parent?.child?.child1?.child2

这样实现和效果和上面的一大长串是一样的。

可选链运算符同样适用于数组:

const array = [1, 2, 3];
array?.[5]

10. 验证undefined和null

如果有这样一段代码:

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

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

a ?? doSomething()

11. 数组元素转化为数字

如果有一个数组,想要把数组中的元素转化为数字,可以使用map方法来实现:

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

通过这种方式,map会在遍历数组时,对数组的每个元素执行Number构造函数并返回结果。

12. 类数组转为数组

可以使用以下方法将类数组arguments转化为数组:

Array.prototype.slice.call(arguments);

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

[...arguments]

13. 对象动态声明属性

如果想要给对象动态声明属性,可以这样:

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

14. 缩短console.log()

每次进行调试时书写很多console.log()就会比较麻烦,可以使用以下形式来简化这个代码:

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

这样每次执行c方法就行了。

15. 获取查询参数

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

window.location.search

如果在想获取到其中某一个参数,可以这样:

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

16. 数字取整

如果有一个数字包含小数,我们想要去除小数,通过会使用math.floor、math.ceil或math.round方法来消除小数。其实可以使用~~运算符来消除数字的小数部分,它相对于数字的那些方法会快很多。

~~3.1415926

实这个运算符的作用有很多,通常是用来将变量转化为数字类型的,不同类型的转化结果不一样:
如果是数字类型的字符串,就会转化为纯数字;
如果字符串包含数字之外的值,就会转化为0;
如果是布尔类型,true会返回1,false会返回0;

除了这种方式之外,我们还可以使用按位与来实现数字的取整操作,只需要在数字后面加上|0即可:

23.9 | 0   // 23
-23.9 | 0   // -23

这个操作也是直接去除数字后面的小数。这个方法和上面方法类似,使用起来性能都会比JavaScript的的API好很多。

17. 删除数组元素

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

18. 检查对象是否为空

如果我们想要检查对象是否为空,可以使用以下方式:

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

Object.keys()方法用于获取对象的 key,会返回一个包含这些key值的数组。如果返回的数组长度为0,那对象肯定为空了。

19. 使用 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…case来改写:

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

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

如果想获取数组中的最后一项,很多时候会这样来写:

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

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

arr.slice(-1)

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

本文链接:http://so.lmcjl.com/news/9677/

展开阅读全文
相关内容