仅将数组的最后一个元素添加到现有数组 [英] Only add last element of an array to existing array
问题描述
我有一个现有的数组,在滚动时,我试图向其中添加更多元素.
I have an existing array that as I scroll, I am trying to add more elements to.
我正在使用 rss2json 将rss供稿转换为json.
I am using rss2json to convert an rss feed to json.
ngOnInit() {
this.getRssFeed(); // returns 4 items
}
这是我添加更多项目的方式:
Here is how I am adding more items:
this.count++;
this.podcastService.getRssFeed(this.rssUrl, this.count)
.then(data => {
if (data) {
for (const episodes of data.items) {
this.episodes.push(episodes); // returns 5 items
// const episode = this.episodes[episodes.length - 1]
}
event.target.complete();
console.log(data);
...
计数正确增加.但是每次调用getRssFeed
时,都会返回整个数组.每次具有正确的长度.
我不确定如何pop
除了最后一个以外的所有返回的数组元素.
Count is correctly getting incremented. But each time getRssFeed
is called the entire array is returned. Each time with the correct length.
I am not sure how to pop
all of the array elements that come back except for the last one.
我也尝试过类似的尝试,并且push()
仅返回最后一个数组元素.还是没有运气.
I've also tried something like this to try and push()
only the last array element returned. Still no luck.
const episode = this.episodes[episodes.length - 1]
例如,如果在初始负载下我得到:
For example, if on initial load I get:
[foo, bar]
当我滚动时,我会回来:
when I scroll, I am getting back:
[foo, bar, baz]
我只想将baz
添加到已经存在的阵列中.
I only want to add baz
to the already existing array.
谢谢您的任何建议!
推荐答案
您可以尝试的一种解决方案是更改下一部分代码:
One solution you can try is to change the next portion of code:
if (data)
{
for (const episodes of data.items)
{
this.episodes.push(episodes); // returns 5 items
// const episode = this.episodes[episodes.length - 1]
}
...
}
通过这个:
if (data)
{
let lastEpisode = data.items.pop();
this.episodes.push(lastEpisode);
...
}
在这里,pop()
用于从data.items
数组中删除最后一个元素并返回该元素,我们将其保存在变量lastEpisode
中,最后将其压入您的episodes
数组中.不会更改data.items
数组的另一种解决方案可能是:
Here, pop()
is used to remove the last element from data.items
array and returns that element, we save it on the variable lastEpisode
and finally we push it on your episodes
array. Another solution, that won't change data.items
array could be:
if (data)
{
let lastEpisode = data.items[data.items.length - 1];
this.episodes.push(lastEpisode);
...
}
这篇关于仅将数组的最后一个元素添加到现有数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!