matkoson
matkoson

Reputation: 13

JavaScript not resetting a variable in a loop

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.

Upvotes: 1

Views: 1776

Answers (1)

Matt
Matt

Reputation: 1082

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]);

Upvotes: 5

Related Questions