Javascript 限制 .map 循环中的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42374873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Limit items in a .map loop
提问by Sydney Loteria
I would like to ask how can I limit my .maploop for example to a 5 items only because currently when I access an api it returns 20 items. but I want to display only 5. Mostly that I found is just looping all throughout the array of objects and not limiting it to a number of items.
我想问一下如何将我的.map循环限制为例如 5 个项目,因为目前当我访问一个 api 时它返回 20 个项目。但我只想显示 5 个。我发现的大部分内容只是在整个对象数组中循环,而不是将其限制为多个项目。
Note: I have no control on the API because I'm just using the moviedb api
注意:我无法控制 API,因为我只是使用 moviedb api
Here's my code:
这是我的代码:
var film = this.props.data.map((item) => {
return <FilmItem key={item.id} film={item} />
});
return film;
回答by Nina Scholz
You could use Array#sliceand take only the elements you need.
您可以Array#slice仅使用和获取您需要的元素。
var film = this.props.data.slice(0, 5).map((item) => {
return <FilmItem key={item.id} film={item} />
});
return film;
If you do not neet the original array anymore, you could mutate the array with seting length to 5and iterate then.
如果您不再需要原始数组,则可以将长度设置为更改数组5并进行迭代。

