简体   繁体   English

如何解释使用 for 循环在 JavaScript 中反转数组

[英]How to explain reversing an array in JavaScript using for loops

I need help with understanding how this code works.我需要帮助来理解这段代码是如何工作的。 task: Without using functions, you must reverse all items in a list.任务:不使用函数,您必须反转列表中的所有项目。 That is, redo it back and forth.也就是说,来回重做。

Example: Input: [-89,71,11,0,4,6] Output: [6,4,0,11,71,-89]示例:输入:[-89,71,11,0,4,6] Output:[6,4,0,11,71,-89]

I found this example, but I need to explain how it works and be able to explain all aspects of the code:我找到了这个例子,但我需要解释它是如何工作的,并且能够解释代码的各个方面:

let arr = [1, 2, 3, 4, 5, 6, 7];
let n = arr.length-1;

for(let i=0; i<=n/2; i++) {
  let temp = arr[i];
  arr[i] = arr[n-i];
  arr[n-i] = temp;
}
console.log(arr);

You can use much simpler like:您可以使用更简单的方法,例如:

const arr = [1, 2, 3, 4, 5]
const reversedArr = []

for (let i = arr.length - 1; i >= 0; i--) {
  reversedArr.push(arr[i])
}

console.log(reversedArr)

Explanation is just, iterating over each item in the original array, but starting from the last item (arr.length = 5 here) and push each of them to a new array.解释只是,迭代原始数组中的每个项目,但从最后一个项目(此处为 arr.length = 5)开始,并将它们中的每一个推入一个新数组。

The code is just doing a reverse function.该代码只是在做一个反向的 function。

The let temp = arr[i];arr[i] = arr[ni];arr[ni] = temp; let temp = arr[i];arr[i] = arr[ni];arr[ni] = temp; is trying to switch the sequence between the i item and the i item from the last element,.正在尝试从最后一个元素切换第i项和第i项之间的序列。

In your code, n is the last element.在您的代码中, n 是最后一个元素。

Example, i =0, temp will equal to be the first element in arr which is 1, and arr[ni] will be the last i element (the last element) which is 7.例如,i = 0, temp将等于arr中的第一个元素,即 1,而arr[ni]将是最后一个 i 元素(最后一个元素),即 7。

Then, the code set arr[i] (first element in arr ) to the last element value arr[ni] which is 7.然后,代码将arr[i]arr中的第一个元素)设置为最后一个元素值arr[ni] ,即 7。

Finally, the code assign the value of the arr[n-1] (last element in arr ) to temp which is 1 and the first element in arr .最后,代码将arr[n-1]arr中的最后一个元素)的值分配给temp ,即 1 和arr中的第一个元素。

So you successfully reverse the first and last element and the loop keep doing the same thing when i=1,2......所以你成功地反转了第一个和最后一个元素,并且当 i=1,2 时循环继续做同样的事情......

 let arr = [1, 2, 3, 4, 5, 6, 7]; let n = arr.length-1; for(let i=0; i<=n/2; i++) { let temp = arr[i]; arr[i] = arr[ni]; arr[ni] = temp; } console.log(arr);

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

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