One issue arises from the iterative process where the value at i
is replaced with i+1
and then moves backwards, resulting in all positions being assigned the last value.
MyShift = function(array) {
for (var i = 0; i < array.length - 1; i++) {
array[i] = array[i + 1];
};
--array.length;
};
var a = ['a', 'b', 'c'];
MyShift(a);
document.body.appendChild(document.createTextNode(a))
During the first iteration, i=1
, and thus array[1] = array[2]
, resulting in [a, c, c]
. Subsequent iteration with i=0
leads to array[0] = array[1]
. Since the previous iteration updated the value of array[1]
, the final array becomes [c, c, c]
.
MyShift = function(array) {
snippet.log('src: ' + array)
for (i = array.length - 2; i >= 0; i--) {
array[i] = array[i + 1];
snippet.log('loop ' + i + ': ' + array);
}
--array.length;
};
var a = ['a', 'b', 'c'];
MyShift(a);
snippet.log('Result: ' + a)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>