The idea is that I should have an array of objects with a length of 4:

const array = [{}, {}, {}, {}]; 

I want the value to always fall into the first position when pushing into this array, and the existing values ​​are shifted to the right. That is, the first value fell into second place, the second - into third, and so on. I thought that the splice() function would help me with this, but this is not what I need. How can I implement my plans without resorting to frameworks?

  • Judging by the ratio of 3: 1, you are not enough to emphasize the requirement of a constant length of the array. Or is it I misunderstood? - Igor
  • @Igor, on the contrary, you understood everything correctly and, apparently, I did make the wrong sentence :) The length of the array should be exactly 4. - JamesJGoodwin

4 answers 4

Unshift

 const t = [1,2,3,4]; t.unshift(5); t.pop(); console.log(t); 

Spread :

 const t = [1,2,3,4]; console.log([5, ...t]); 

     var arr = [1, 2, 3, 4]; arr.splice(0, 0, 123); arr.length = 4; console.log(arr); 

      Did not have time but still ..

        const myArr = [1,2,3,4]; myArr.unshift(0); alert(myArr); 

        Try:

         var a = [23, 45, 12, 67]; a.unshift(34); console.log(a); // [34, 23, 45, 12, 67]