首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >.splice未正确删除元素

.splice未正确删除元素
EN

Stack Overflow用户
提问于 2019-12-12 14:53:52
回答 1查看 1K关注 0票数 1

我使用ngFor let let i = index;,然后将i传递到拼接中,它删除了所有的json元素,只有一个元素。代码的watchingGroup部分很好地拼接。只是this.posts不能正常工作。

<div class="row" *ngFor="let post of posts;let i = index;">

单击该按钮执行函数时,将运行

this.posts = this.posts.splice(i, 1);

为什么它不从i中删除指定的元素?

代码语言:javascript
复制
 removeFromWatchList(id: string, watchingGroup: string[], i) {


    var index = watchingGroup.indexOf(this.userId); // <-- Not supported in <IE9

    if (index !== -1) {
      watchingGroup.splice(index, 1);
    }
    console.log(watchingGroup);
    var unique = watchingGroup.filter(function(elem, index, self) {
      return index === self.indexOf(elem);
    });
    this.uniqueResult = unique;


    this.watchListService

      .addToWatchList(auctionId, this.uniqueResult)
      .subscribe(
        res => {
          this.counter++;
          console.log("COUTNER: " + this.counter);

          console.log("SUCCESS");
        },
        err => {
          // Handle error response
          console.log("ERROR");
        }
      );

      this.posts = this.posts.splice(i, 1);


  }
代码语言:javascript
复制
  <div class="row" *ngFor="let post of posts;let i = index;">
      <div class="col-md-9 col-centered">

        <div class="listingCard" [@simpleFadeAnimation]="'in'" >

          <div class=container>
            <div class="row"> </div>

            <div class="row">

              <div class="col-md-5">

                <button id="watchListButton" type="button" mat-raised-button (click)="removeFromWatchList(post.id, post.watchingGroup, i)"
                  [ngStyle]="{ 'background-color': (this.watchListItems ? 'green' : 'white'),'background-color': (!this.watchListItems ? 'white' : 'white') }">{{watchButtonValue}}</button>
              </div>
            </div>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-12 15:00:13

变异原始数组并从数组中返回删除的项,从MDN的语法可以看出:

var arrDeletedItems = array.splice(start[,deleteCount[,item1[,item2,.]])

因此,您应该直接看到posts中的变化。不要这样reassign

代码语言:javascript
复制
this.posts = this.posts.splice(i, 1);

只要这样做就行了:

代码语言:javascript
复制
this.posts.splice(i, 1);
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59307245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档