简体   繁体   English

JS .splice不单独返回数组中已删除的项目

[英]JS .splice returns removed items in array not by itself

Hopefully I can make sense with this. 希望我对此有所了解。

Array.splice function returns an array containing all removed elements. Array.splice函数返回包含所有已删除元素的数组。

In my code, I'm only removing one element at a time but I need to store that removed item. 在我的代码中,我一次只删除一个元素,但是我需要存储该删除的项目。

I'm doing this : 我正在这样做:

let toRem = $(this).closest("li");  

let temp = list.splice(toRem.index(), 1);
compList.push(temp[0]);
compList[compList.length - 1].completed = new Date;

toRem.remove();

Adding the temp array seems like such a waste but I can't see another way to do this. 添加临时数组似乎很浪费,但是我看不到另一种方法。 I understand if this is such a tiny thing that I shouldn't care about but I want to make this that much better if possible. 我知道这是否是一件我不应该在意的小事情,但是我想尽可能地改善它。

You should be able to combine the lines: 您应该能够合并以下几行:

compList.push(list.splice(toRem.index(), 1)[0]);

Or if you don't want to do that, you could use destructuring: 或者,如果您不想这样做,则可以使用解构:

let [temp] = list.splice(toRem.index(), 1);
compList.push(temp);

Well, this entirely depends on what you mean by better. 好吧,这完全取决于您所说的更好。 There is readability, which is usually (but not always) being more verbose ie what you have now, and then there is making the code as short as you can. 有可读性,通常(但不总是)更加冗长,即您现在拥有的内容,然后使代码尽可能短。

If you have an issue with the temp variable, there is no need to use it: 如果您对temp变量有疑问,则无需使用它:

compList.push(list.splice(toRem.index(), 1)[0]);

You could then improve upon this by making it less dependant on the size of the splice: 然后,可以通过减少对接头大小的依赖来改进此方法:

compList.push(...list.splice(toRem.index(), 1));

The .push can accept any number of inputs and the spread ( ... ) operater will split an array into an input per item in the array. .push可以接受任意数量的输入,并且spread( ... )运算符会将数组拆分为每个数组中每个项目的输入。

Or, if you know there is always only going to be one element spliced, you could combine all three lines: 或者,如果您知道总是只有一个元素被拼接,则可以合并所有三行:

compList.push({ ...list.splice(toRem.index(), 1)[0], completed: new Date() });

As you can see though, as each version gets shorter or 'better' in one way, it loses out on readability. 如您所见,随着每个版本以一种方式变得更短或“更好”,它失去了可读性。

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

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