只有增加一个阵列现有阵列的最后一个元素

问题描述 投票:0回答:2

我有一个现有的阵列,作为我滚动,我想加入更多的元素来。

我使用rss2json转换RSS提要的JSON。

 ngOnInit() {
    this.getRssFeed();  // returns 4 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所有前来除了最后一回数组元素。

我也尝试过这样的事情,试图push()只有最后一个数组元素返回。仍然没有运气。

const episode = this.episodes[episodes.length - 1] 

例如,如果在初始加载我得到:

[foo, bar]

当我滚动,我找回:

[foo, bar, baz]

我只想baz添加到现有阵列。

谢谢你的任何建议!

javascript arrays angular ionic-framework
2个回答
1
投票

一种解决方案可以尝试是改变代码的下部分:

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阵列可以是:

if (data)
{
    let lastEpisode = data.items[data.items.length - 1];
    this.episodes.push(lastEpisode);
...
}

0
投票

据我了解,你想补充一点,最新的项目从getRssFeed服务到episodes列表返回。您可以利用阵列蔓延语法对getRssFeed服务的每个电话更新的剧集列表。

您可以更新的功能,使它看起来像这样:

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);
        ...
© www.soinside.com 2019 - 2024. All rights reserved.