简体   繁体   English

JavaScript 创建数组 with.map() 与空项目(稀疏数组)

[英]JavaScript create array with .map() with empty items (sparse array)

Say I have an array说我有一个数组

[1,2,1,2,1];

I want to use .map() to return a new array which is the same as the old one but the item is missing in the new array if it was 2 in the old one.我想使用.map()返回一个与旧数组相同的新数组,但如果旧数组中为 2,则新数组中缺少该项目。 So the new array would be:所以新数组将是:

const newArray = [1, ,1, ,1];

So the code would look something like:所以代码看起来像:

const newArray = [1,2,1,2,1].map(d => d === 1 ? d : "not sure how to return empty item here");

But I don't know what to return to make the array have a missing element.但我不知道要返回什么来使数组缺少元素。

edit: I suggested using .map() because I didn't realise it is not possible to go from an array to sparse array (as helpfully explained in their comment below).编辑:我建议使用.map()因为我没有意识到 go 从一个数组到稀疏数组是不可能的(正如他们在下面的评论中有用的解释)。 In this case a solution not using .map() is OK.在这种情况下,不使用.map()的解决方案是可以的。

You need to return undefined :您需要返回undefined

 const newArray = [1,2,1,2,1].map(d => d === 1? d: undefined); console.log(newArray);

This is an example on how empty elements are treated in JavaScript:这是在 JavaScript 中如何处理空元素的示例:

 arr = [1,2,3]; newArr = arr.concat([, , , 5,6]); console.log(newArr);

You could just return null :你可以只返回null

const newArray = [1,2,1,2,1].map(d => d === 1 ? d : null);
const array = [1,2,1,2,1];
const newArray = Array(array.length);

array.map((item, index) => item !==2 ? newArray[index] = item : null);

// newArray -> [ 1, <1 empty slot>, 1, <1 empty slot>, 1 ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM