1、数组合并
const start = [1, 2]
const end = [5, 6, 7]
const numbers = [9, ...start, ...end, 8] // [9, 1, 2, 5, 6, 7 , 8]
// 或者使用
const start = [1, 2, 3, 4]
const end = [5, 6, 7]
start.concat(end); // [1, 2, 3, 4, 5, 6, 7]
// PS 但是使用concat()方法时,如果需要合并的数组很大,那么concat() 函数会在创建单独的新数组时消耗大量内存。这时可以使用以下方法来实现数组的合并:
Array.prototype.push.apply(start, end)
// 通过这种方法能很大成都上较少内存的使用
2、对象验证
const parent = {
child: {
child1: {
child2: {
key: 10
}
}
}
}
//很多时候我们会这样去写,避免某一层级不存在导致报错:
parent && parent.child && parent.child.child1 && parent.child.child1.child2
这样代码看起来就会很臃肿,可以使用JavaScript的可选链运算符:
语法如下:
obj?.prop
obj?.[expr]
arr?.[index]
func?.(args)
parent?.child?.child1?.child2
3、取数组最后一个值
const arr = [1, 2, 3, 4, 5];
arr[arr.length - 1] // 5
或者:
arr.slice(-1);