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.

matkoson
  • 13
  • 3
  • 2
    because `splice` modifies the array in place. – Hunter McMillen Apr 09 '18 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()` – Matt Apr 09 '18 at 16:56
  • 1
    Possible duplicate of [Looping through array and removing items, without breaking for loop](https://stackoverflow.com/questions/9882284/looping-through-array-and-removing-items-without-breaking-for-loop) – Mohammad Usman Apr 09 '18 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. – Matt Apr 09 '18 at 17:08
  • If that answer was helpful can you mark it as the answer? – Matt Apr 16 '18 at 17:49

1 Answers1

4

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]);
Matt
  • 1,062
  • 1
  • 8
  • 11