简体   繁体   English

如何在具有偏移号的数组上使用解构

[英]how to use destructuring on an array with an offset number

I have an array of objects which are dynamic data from a CMS. 我有一组对象,这些对象是来自CMS的动态数据。 I want to be able to split them based on an offset number. 我希望能够根据偏移量对它们进行拆分。 I tried using destructuring but got an error the way I was using it. 我尝试使用解构,但是在使用过程中出现了错误。

uncaught SyntaxError: rest element must be last element 未捕获的SyntaxError:rest元素必须是最后一个元素

I first tried this simple setup where I could separate the last item from the firstItems but I found out you can't use destructuring like this. 我首先尝试了这种简单的设置,可以在其中将最后一个项目与firstItems分开,但是我发现您不能使用像这样的解构。

const cmsData = [{..},{..},{..},{..}]
const arr = [...firstItems, last] = cmsData

What I'm trying to do is have a function where I can pass it an offset value so it would give me the first items up to the offset number and then last would be the the offset number items. 我想做的是有一个函数,可以在其中传递一个偏移值,这样它将使我得到的第一个项目直到偏移号,然后最后是偏移号项目。 for example. 例如。

const offset = 2;
const cmsData = [{..},{..},{..},{..}]
firstItems = [{..},{..}];
last = [{..},{..}];

If offset = 3 the last would be the last 3. 如果offset = 3,则最后一个为最后3个。

You can use Array.slice() with a negative offset : 您可以使用具有负偏移量的 Array.slice()

 const offset = 3; const cmsData = [1, 2, 3, 4]; const firstItems = cmsData.slice(0, -offset); const lastItems = cmsData.slice(-offset); console.log(firstItems); console.log(lastItems); 

Just use Array.prototype.slice : 只需使用Array.prototype.slice

firstItems = cmsData.slice(0, cmsData.length - offset);
last = cmsData.slice(cmsData.length - offset);

You can only use that sort of syntax at the end of an array - it doesn't work at the beginning, as you can see. 您只能在数组的末尾使用这种语法-如您所见,它在开始时不起作用。 Use .slice instead: 使用.slice代替:

 const cmsData = [0, 1, 2, 3]; const firstItems = cmsData.slice(0, cmsData.length - 1); const last = cmsData[cmsData.length - 1]; console.log(firstItems); console.log(last); 

Or, to get multiple items from the end: 或者,要从头获得多个项目:

 const cmsData = [0, 1, 2, 3]; const offset = 2; const firstItems = cmsData.slice(0, cmsData.length - offset); const last = cmsData.slice(cmsData.length - offset); console.log(firstItems); console.log(last); 

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

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