1

would like to ask for reason, why JavaScript doesn't reset a variable after every iteration of the loop, in situation when I try to set it equal to a function argument(#1). It does the reset, if the variable is equaled to a specific array(#2).

#1
    function almostIncreasingSequence(sequence) {
            for (var i = 0; i < sequence.length; i++) {
                var testArray=sequence;
                testArray.splice(i, 1);
                console.log(testArray);
            }
        }
        almostIncreasingSequence([1, 3, 2, 1]);
#2
    function almostIncreasingSequence(sequence) {
            for (var i = 0; i < sequence.length; i++) {
                var testArray=[1, 3, 2, 1];
                testArray.splice(i, 1);
                console.log(testArray);
            }
        }
        almostIncreasingSequence([1, 3, 2, 1]);

Will be grateful for every answer. Thank you.

5
  • 2
    because splice modifies the array in place. Commented Apr 9, 2018 at 16:55
  • 2
    Your var testArray=sequence isn't creating a new array but just referencing sequence. So when you splice testArray you are also splicing sequence. If you want it to reset then you need var testArray = sequence.slice() Commented Apr 9, 2018 at 16:56
  • 1
    Possible duplicate of Looping through array and removing items, without breaking for loop Commented Apr 9, 2018 at 16:57
  • 1
    @MohammadUsman His issue isn't understanding that splicing removes the index while the loop proceeds causing the occasional skipped index. His issue is not understanding variable assignment(s) and what passes a reference and what passes a value. Please remove or update your comment. Commented Apr 9, 2018 at 17:08
  • If that answer was helpful can you mark it as the answer? Commented Apr 16, 2018 at 17:49

1 Answer 1

5

As stated in the comment above is that you have confusion with your variable assignment.

In #1 you are under the impression that var testArray = sequence; is the same as saying var testArray = [1, 3, 2, 1]. This isn't the case. var testArray = sequence is simply a reference to sequence. Whatever you modify in testArray calls back to sequence and modifies it there as well.

To fix #1 to perform as #2 you will have to do var testArray = sequence.slice(). This performs a shallow copy of sequence so that modifying testArray has no impact on sequence.

function almostIncreasingSequence(sequence) {
  for (var i = 0; i < sequence.length; i++) {
      var testArray=sequence.slice();
      testArray.splice(i, 1);
      console.log(testArray);
  }
}

almostIncreasingSequence([1, 3, 2, 1]);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.