当前位置: 动力学知识库 > 问答 > 编程问答 >

What's causing the infinite loop in my javascript for statement?

问题描述:

When the for loop is entered, it never stops:

 remove: function remove(e) {

var objectToRemoveId = e.currentTarget.getAttribute('objectId').toString();

var filteredList = this.myDto.objectList;

for (var index = 0; index < this.myDto.objectList.length; index++) {

var currentObject = this.myDto.objectList[index];

if (currentObject.Id !== objectToRemoveId) {

filteredList[filteredList.length + 1] = timeSheet;

}

}

}

Assumed that the this.myDto.ObjectList is an array with one element in it. I'm sure the problem is just staring me in the face, but I can't figure it out.

网友答案:

You're adding to the same list in your loop, so every time you loop through, your this.myDto.objectList.length goes up one. It seems like you would want an empty array here:

var filteredList = this.myDto.objectList;

Like this:

var filteredList = [];

Or a copy, like this:

var filteredList = this.myDto.objectList.slice();

I'm not sure what the end result is supposed to be, adding to a list named filtered is throwing me off, but in either case, you're probably after one of the solutions above.

网友答案:

It is because you are modifying the list you are iterating over, increasing its length each iteration, thus the index is always 1 less than the length of the array.

The confusion is probably because of the reference:

var filteredList = this.myDto.objectList;

However you are still using the this.myDto.objectList reference in the loop, which is probably why you didn't spot it.

网友答案:

Can't you do something like this to make it less confusing?

 remove: function remove(e) {
     var objectToRemoveId = e.currentTarget.getAttribute('objectId').toString();
     var filteredList = new Array();

     for (var index = 0; index < this.myDto.objectList.length; index++) {
          var currentObject = this.myDto.objectList[index];

       if (currentObject.Id !== objectToRemoveId) {
         filteredList[index] = timeSheet;
       }
     }
   } 
网友答案:

There are two errors that together cause the infinite loop:

  1. filteredList is a reference to this.myDto.objectList - both variables refer to the same object. When you append increase the length of filteredList, you also increase the length of myDto.objectList. The solution to this part of the problem is use the .slice() method to copy the array.

  2. Additionally, you're using the strict comparison operator (!==) to look for your objectToRemoveId. Since the id is likely stored as a numeric value and you call .toString() on the attribute, these values can never be equal and thus you fall into the if statement every time through the loop.

Put the two together, and as you loop over your array you end up adding one term to the array on every iteration.

分享给朋友:
您可能感兴趣的文章:
随机阅读: