简体   繁体   English

带有splice()方法的反向数组

[英]Reverse array with with splice() method

I'm following a course of learning Javascript, saw this code but don't know exactly how it works. 我正在学习Javascript的课程,看到了这段代码,但不知道它是如何工作的。 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 assuming you're speaking of this part specifically (not the dom interaction) 我假设您是专门讲这部分(不是dom交互)

the simplest way to see it is to add a console.log() 最简单的查看方法是添加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 . 当查看输出时,可以看到该函数将最后一个元素复制到索引为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 . 在这种情况下,它将复制第3项和第4项之间的最后一项( 7 ),即索引3位置。 Then removes the 7 然后取出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: 首先,让我们阅读Array.splice()的作用:

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements. splice()方法通过删除或替换现有元素和/或添加新元素来更改数组的内容。

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

  • start : Index at which to start changing the array (with origin 0). start :开始更改数组的索引(原点为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. 如果为负数,将从数组末尾开始许多元素(以原点-1开头,这意味着-n是第n个最后一个元素的索引,因此等效于array.length-n的索引),并将其设置为如果绝对值大于数组的长度,则为0。
  • deleteCount (Optional): An integer indicating the number of old array elements to remove. deleteCount (可选):一个整数,指示要删除的旧数组元素的数量。 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. 如果省略deleteCount,或者其值等于或大于array.length-开始(即,如果等于或大于数组中剩余的元素数量,则从start开始),则所有从数组开始到结尾的所有元素都将被删除。 If deleteCount is 0 or negative, no elements are removed. 如果deleteCount为0或负数,则不会删除任何元素。 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. item1,item2,... (可选):要添加到数组的元素,从起始索引开始。 If you don't specify any elements, splice() will only remove elements from the array. 如果不指定任何元素,则splice()只会从数组中删除元素。

You should first note that splice() mutates the original array. 您首先应该注意, splice() 改变原始数组。 So, on every iretarion of the loop, basically you are performing these actions: 因此,在循环的每个循环上,基本上您都在执行以下操作:

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

Add the last element of the current array at the position i . 在位置i处添加当前数组的最后一个元素。

a.splice(j, 1); 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 . 这将在索引i处添加一个新项目。 And the new item added is the last item of the array 并且添加的新项目是array的最后一项

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

This line removes the last item of the array which is added at index i . 这行删除在索引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] (completely reversed) [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] (完全颠倒)

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 come back here. 看到这个array.splice ,然后回到这里。

Now that you know what array.splice() does. 现在您知道array.splice()的作用。

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 i th index of a 这部分代码需要的当前最后一个元件([J - 1]),并把它在第i索引

and shifts the elements to the right of i th index by one position. 并将元素向第i个索引的右边移动一个位置。

EXAMPLE-1 in first step: 第一步中的Example-1

i = 0 我= 0

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

j = a.length j =长度

a[j - 1] = 10 a [j-1] = 10

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

a = [10,1,2,3,4,5,6,7,8,9,10] 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 在这一步中,我们删除留额外的最后一个元素之后第1步

From EXAMPLE-1 we see that length of a has increased by 1 unit. 从例1中我们看到a的长度增加了1个单位。

So in this step we take the last element of a (now a[j] ) and remove it. 因此,在这个步骤中,我们采取最后一个元素( 现[J]),并删除它。

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

Now for i = 1 现在因为我= 1

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

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

This process is repeated till i == a.length ie no more elements left to rotate. 重复此过程,直到i == a.length,即不再剩余要旋转的元素。

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM