最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Reverse array with with splice() method - Stack Overflow

programmeradmin2浏览0评论

I'm following a course of learning Javascript, saw this code but don't know exactly how it works. Basically what it does is reverse the numbers in the array.

Anyone who has a deeper understanding and would like to explain me of what the code does exactly?

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var knop = document.getElementById("knop");
knop.addEventListener("click", reverse);

function reverse() {
  for (var i = 0, j = a.length; i < a.length; i++) {
    a.splice(i, 0, a[j - 1]);
    a.splice(j, 1);
  }
  document.getElementById("demo1").innerHTML = a;
}
   <p id="demo1">Hier komt de inhoud na het omkeren</p>
    <button type="button" id="knop">Keerom</button>

I'm following a course of learning Javascript, saw this code but don't know exactly how it works. Basically what it does is reverse the numbers in the array.

Anyone who has a deeper understanding and would like to explain me of what the code does exactly?

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var knop = document.getElementById("knop");
knop.addEventListener("click", reverse);

function reverse() {
  for (var i = 0, j = a.length; i < a.length; i++) {
    a.splice(i, 0, a[j - 1]);
    a.splice(j, 1);
  }
  document.getElementById("demo1").innerHTML = a;
}
   <p id="demo1">Hier komt de inhoud na het omkeren</p>
    <button type="button" id="knop">Keerom</button>

Share Improve this question asked Mar 5, 2019 at 15:58 NiekketNiekket 731 silver badge8 bronze badges 2
  • Array.prototype.splice(start[, deleteCount[, item1[, item2[, ...]]]]): "The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place." – Andreas Commented Mar 5, 2019 at 16:05
  • 1 Interesting question! In short it set's j as the number of indexes within the array j = a.length;. Then it counts backwards with j - 1 (counting down to zero) Then, it uses splice to set the new value for the current array index (counting up from 0) -- effectively reversing the order of the array. – Zak Commented Mar 5, 2019 at 16:06
Add a ment  | 

5 Answers 5

Reset to default 4

I'm assuming you're speaking of this part specifically (not the dom interaction)

the simplest way to see it is to add a console.log()

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var i = 0, j = a.length; i < a.length; i++) {
  a.splice(i, 0, a[j - 1]);
  console.log('index:',  i)
  console.log('copy:',  a.join(','))
  a.splice(j, 1);
  console.log('trim:',  a.join(','))
}

when you look at the output, you can see that the function copies the last element to the array at index i. Then it removes the last item. It does this as many times as there are items in the array

example:

In this case, it copies the last item (7) between 3rd and 4th item, position at index 3. Then removes the 7

index: 3
copy: 10,9,8,7,1,2,3,4,5,6,7
trim: 10,9,8,7,1,2,3,4,5,6

First, lets read what Array.splice() does:

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements.

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

  • start: Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin -1, meaning -n is the index of the nth last element and is therefore equivalent to the index of array.length - n) and will be set to 0 if absolute value is greater than the length of the array.
  • deleteCount (Optional): An integer indicating the number of old array elements to remove. If deleteCount is omitted, or if its value is equal to or larger than array.length - start (that is, if it is equal to or greater than the number of elements left in the array, starting at start), then all of the elements from start through the end of the array will be deleted. If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element (see below).
  • item1, item2, ... (Optional): The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.

You should first note that splice() mutates the original array. So, on every iretarion of the loop, basically you are performing these actions:

a.splice(i, 0, a[j - 1]);

Add the last element of the current array at the position i.

a.splice(j, 1);

Remove the last element on the array.

This will be easy to check if we add some logs:

var a = [1, 2, 3, 4, 5];

var knop = document.getElementById("knop");
knop.addEventListener("click", reverse);

function reverse()
{
  for (var i = 0, j = a.length; i < a.length; i++)
  {
    console.log("-----------------");
    console.log("Iteration: " + i);
    console.log("-----------------");
    console.log(`array before insert at position ${i}: ${a}`);
    a.splice(i, 0, a[j - 1]);
    console.log(`array after insert at position ${i}: ${a}`);
    a.splice(j, 1);
    console.log(`array after delete last element: ${a}`);
  }
  document.getElementById("demo1").innerHTML = a;
}
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
<p id="demo1">Hier komt de inhoud na het omkeren</p>
<button type="button" id="knop">Keerom</button>

knop.addEventListener("click", reverse); //attaches the eventListener to the variable `knop` so when the it will clicked it will trigger `reverse` event.

//This creates a loop which runs through whole array.
for (var i = 0, j = a.length; i < a.length; i++) {
    a.splice(i, 0, a[j - 1]);
    a.splice(j, 1);
  }

This add a new item at index i. And the new item added is the last item of the array

a.splice(i, 0, a[j - 1]);

This line removes the last item of the array which is added at index i.

a.splice(j, 1);

Below is example how array changes

[1,2,3,4,5,6] => [6,1,2,3,4,5] => [6,5,1,2,3,4] => [6,5,4,1,2,3] => [6,5,4,3,1,2] => [6,5,4,3,2,1](pletely reversed)

The code start removing elements from last and adding them to their position which should be in reversed array. For example:

  • last will be moved to 1st place
  • Second last will be moved to second place
  • Second to second last place
  • First will be moved to last place

See this array.splice and then e back here.

Now that you know what array.splice() does.

Here basically two things are happening:

1. a.splice(i, 0, a[j - 1]);

This part of code takes the current last element of a(a[j - 1]) and puts it at the ith index of a

and shifts the elements to the right of ith index by one position.

EXAMPLE-1 in first step:

i = 0

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

j = a.length

a[j - 1] = 10

result of a.splice(i, 0, a[j - 1]); is

a = [10,1,2,3,4,5,6,7,8,9,10]

2. a.splice(j, 1);

In this step we remove extra last element left in a after Step-1

From EXAMPLE-1 we see that length of a has increased by 1 unit.

So in this step we take the last element of a(now a[j]) and remove it.

to get resultant a = [10,1,2,3,4,5,6,7,8,9]

Now for i = 1

a.splice(i, 0, a[j - 1]); gives a = [10,9,1,2,3,4,5,6,7,8,9] and

a.splice(j,1); gives a = [10,9,1,2,3,4,5,6,7,8]

This process is repeated till i == a.length i.e no more elements left to rotate.

Maybe it is easier to use only one variable as index for changing.

It takes the element from index zero and splice (insert) it at the conting down index.

function reverse() {
    var i = a.length;
    while (i--) {
        console.log(...a);
        a.splice(i, 0, a.splice(0, 1)[0]);
    }
    document.getElementById("demo1").innerHTML = a;
}

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var knop = document.getElementById("knop");
knop.addEventListener("click", reverse);
<p id="demo1">Hier komt de inhoud na het omkeren</p>
<button type="button" id="knop">Keerom</button>

发布评论

评论列表(0)

  1. 暂无评论