最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

angular - splice can't remove the first element in javascript - Stack Overflow

programmeradmin2浏览0评论

In angular2, my HTML is calling removeThisForm in javascript. The event is an object of File Array. For each object in File Array, I generate a form in angular2.

(click)=removeThisForm(event)

In javascript, I am trying to remove the file that is passing in.

removeThisForm(file) {
    var removableIndex = arr.indexOf(file);
    if (removeIndex >= 0) {
        arr = arr.splice(removableIndex);
    } 

I am able to remove any form passing in, except the first one. I tried shift(), slice() and splice(0,1). When I did splice(0,1), I am getting an error of "Form submission canceled because the form is not connected".

In angular2, my HTML is calling removeThisForm in javascript. The event is an object of File Array. For each object in File Array, I generate a form in angular2.

(click)=removeThisForm(event)

In javascript, I am trying to remove the file that is passing in.

removeThisForm(file) {
    var removableIndex = arr.indexOf(file);
    if (removeIndex >= 0) {
        arr = arr.splice(removableIndex);
    } 

I am able to remove any form passing in, except the first one. I tried shift(), slice() and splice(0,1). When I did splice(0,1), I am getting an error of "Form submission canceled because the form is not connected".

Share Improve this question asked Mar 21, 2017 at 15:55 Matt-powMatt-pow 9864 gold badges18 silver badges34 bronze badges 1
  • Try arr.splice(removableIndex,1); – Karthik VU Commented Mar 21, 2017 at 15:57
Add a ment  | 

1 Answer 1

Reset to default 6

You've omitted to pass second argument to the Array.prototype.splice method (an integer representing the number of elements to be deleted). Try this:

removeThisForm(file) {
    var removableIndex = arr.indexOf(file);
    if (removeIndex >= 0) {
        arr.splice(removableIndex, 1);
    } 
}

Also, the Array.prototype.splice method returns an array containing the deleted elements. Therefore, you can't say:

arr = arr.splice(removableIndex, 1);

as it will override your arr with the returned value of Array.prototype.splice method.

发布评论

评论列表(0)

  1. 暂无评论