简体   繁体   English

从 Typescript/Javascript 中的数组返回/获取 x 个项目

[英]Return / Get x Number of Items From an Array in Typescript/Javascript

I have an array with over 200 items from a.json file.我有一个数组,其中包含来自 a.json 文件的 200 多个项目。

I want to know how I can return lets say the first 10 items or 20 items starting from the 7th index/item.我想知道如何返回让我们说从第 7 个索引/项目开始的前 10 个项目或 20 个项目。

Example例子

OriginalArray = [{a}, {b}, {c}, {d}, {e}, {f}, {g}, {h}, {i}, {j}, {k}, {l}]

How do I get newArray = [{a}, {b}, {c}, {d}] or newArray = [{e}, {f}, {g}, {h}]如何获得newArray = [{a}, {b}, {c}, {d}]newArray = [{e}, {f}, {g}, {h}]

from the originalArray in typeScript or Javascript.来自 typeScript 或 Javascript 中的originalArray

Thank you谢谢

Try this:尝试这个:

newArrayA = OriginalArray.slice(0, Math.round(OriginalArray.length/2)) // first half
newArrayB = OriginalArray.slice(Math.round(OriginalArray.length/2)) // second half

You need slice你需要切片

 const offset = 7; console.log( ["{a}", "{b}", "{c}", "{d}", "{e}", "{f}", "{g}", "{h}", "{i}", "{j}", "{k}", "{l}"].slice(offset,offset+4) )

In your case:在你的情况下:

var newArray = OriginalArray.slice(7, 7+20);

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

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