Only add last element of an array to existing arra

2019-08-31 01:37发布

问题:

I have an existing array that as I scroll, I am trying to add more elements to.

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);
            ...

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.

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]

I only want to add baz to the already existing array.

Thank you for any suggestions!

回答1:

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]
    }
...
}

By this one:

if (data)
{
    let lastEpisode = data.items.pop();
    this.episodes.push(lastEpisode);
...
}

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);
...
}


回答2:

From what I understand, you want to add just the latest items returned from the getRssFeed service to the episodes list. You can make use of the Array spread syntax to update the episodes list on every call of the getRssFeed service.

You can update the function to make it look like this:

this.count++; 
this.podcastService.getRssFeed(this.rssUrl, this.count)
    .then(data => {
        if (data) {
            this.episodes = [
               // This keeps the previous episodes
               ...this.episodes,
               // This adds the last item returned to the array
               data.items[data.items.length -1],
            ]
        }
        event.target.complete();
        console.log(data);
        ...