How to write a shift function without splicing

I am trying to write functions for some basic array methods, but now I'm stuck on re-creating the shift without using splicing. Any advice would be greatly appreciated.

MyShift = function (array) {
    for (i = array.length - 2; i >= 0; i--) {
        array[i] = array[i + 1];
    }
    --array.length;
};
+4
source share
3 answers

Due to the way you iterate, you change the value iwith i+1and then move backward, so you assign the last value to all positions

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))
Run codeHide result

, , i=1, array[1] = array[2], [a, c, c], i=0, array[0] = array[1], arra[1], [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.imtqy.com/simple-snippets-console/snippet.js"></script>
Hide result
+5

You can do something like this.

MyShift = function (array) {
    for (i =0; i<array.length; i++) {
        array[i] = array[i + 1];
        console.log(array[i]);
    }
    --array.length;
    return(array);
}; 
MyShift([1,2,3,4]);

Hope this helps

0
source

Source: https://habr.com/ru/post/1614099/


All Articles