简体   繁体   English

javascript unshift pop 在一个循环中

[英]javascript unshift pop in a loop

I'm studying JS and I have this exercise that is asking to reverse an array in place (without the use of a second array) and without the use of 'reverse'.我正在学习 JS 并且我有这个练习要求在适当的位置反转数组(不使用第二个数组)并且不使用“反转”。 Although I already have the solution to the exercise I don't understand why my solution does not work, here it is:虽然我已经有了练习的解决方案,但我不明白为什么我的解决方案不起作用,这里是:

 function reverseArrayInPlace (arr){ const k = arr[0]; while (arr[arr.length-1] !== k){ arr.unshift(arr.pop()); } return arr; } console.log(reverseArrayInPlace(arr1));

You take the end of the array and put it at the first position:您取出数组的末尾并将其放在第一个位置:

 [1, 2, 3]
 [3, 1, 2]
 [2, 3, 1]
 [1, 2, 3]

as you can see that actually doesnt reverse anything.正如你所看到的,实际上并没有逆转任何东西。

It will not work if your array contains duplicates of the first element.如果您的数组包含第一个元素的重复项,它将不起作用。 As you are taking the first element as key, whenever any duplicate element becomes the last element, your loop exits.当您将第一个元素作为键时,只要任何重复元素成为最后一个元素,您的循环就会退出。

Try this, just check if the two elements being selected is equal or not, if equal do not swap else swap.试试这个,只检查被选择的两个元素是否相等,如果相等不交换否则交换。 Iterate till the pointer k is <= the pointer j .迭代直到指针k <=指针j

 function reverseArrayInPlace (arr){ let first = 0; let last = arr.length - 1; let k = first, j = last; while(k <= j){ if(arr[k] !== arr[j]){ let temp = arr[k]; arr[k] = arr[j]; arr[j] = temp; } k++; j--; } return arr; } arr1 = [1, 2, 3, 4]; console.log(reverseArrayInPlace(arr1)); arr1 = [1, 2, 3]; console.log(reverseArrayInPlace(arr1));

This method will solve the problem without pop or unshift.这种方法将解决问题,而不会弹出或取消移位。 Try this.尝试这个。

 function reverseArray(array) {
 for (let i = 0; i < Math.floor(array.length / 2); i++) {
 let oldArray = array[i];
 array[i] = array[array.length - 1 - i];
 array[array.length - 1 - i] = oldArray;
 }
 return array;
 }
 console.log(reverseArray([1,2,3]));

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

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