1、数组合并

  1. const start = [1, 2]
  2. const end = [5, 6, 7]
  3. const numbers = [9, ...start, ...end, 8] // [9, 1, 2, 5, 6, 7 , 8]
  4. // 或者使用
  5. const start = [1, 2, 3, 4]
  6. const end = [5, 6, 7]
  7. start.concat(end); // [1, 2, 3, 4, 5, 6, 7]
  8. // PS 但是使用concat()方法时,如果需要合并的数组很大,那么concat() 函数会在创建单独的新数组时消耗大量内存。这时可以使用以下方法来实现数组的合并:
  9. Array.prototype.push.apply(start, end)
  10. // 通过这种方法能很大成都上较少内存的使用

2、对象验证

  1. const parent = {
  2. child: {
  3. child1: {
  4. child2: {
  5. key: 10
  6. }
  7. }
  8. }
  9. }
  10. //很多时候我们会这样去写,避免某一层级不存在导致报错:
  11. parent && parent.child && parent.child.child1 && parent.child.child1.child2
  12. 这样代码看起来就会很臃肿,可以使用JavaScript的可选链运算符:
  13. 语法如下:
  14. obj?.prop
  15. obj?.[expr]
  16. arr?.[index]
  17. func?.(args)
  18. parent?.child?.child1?.child2

3、取数组最后一个值

  1. const arr = [1, 2, 3, 4, 5];
  2. arr[arr.length - 1] // 5
  3. 或者:
  4. arr.slice(-1);