如何在给定数组上使用方法之前忽略检查数组长度?

Nal*_*hin 0 javascript arrays

在我的项目中,我有很多动态填充的数组。每当我想在数组上使用过滤器,映射或任何其他方法时,有什么方法可以跳过检查数组长度的方法吗?

const newArray = array.length ? array.filter(n=>n.id=id) : [];

const otherArray = array.length ? array.map(n=>n.id=id) : [];
Run Code Online (Sandbox Code Playgroud)

Kyr*_*nko 6

您不必检查它们。

const testArr = [];

const anotherArr = testArr.map((item) => { 
  // do something with item;
  return transformedItem;
});

// anotherArr is [];

const anotherArr2 = testArr.filter((item) => { 
  // do something with item;
  return boolean;
});

// anotherArr2 is still [];
Run Code Online (Sandbox Code Playgroud)