我正在尝试解决以下问题:
I'm trying to solve the following exercise:
不使用反向方法而不使用$ b $来反转数组b第二个数组,并且不重复任何值。
Reverse an array without using the reverse method, without using a second array, and without duplicating any of the values.
我已经考虑过使数组成为对象,然后更新数组从头到尾,但我认为您也可以对其进行更新。
I've thought about making the array an object and then updating the array from the end to the beginning but I figured you can just update it as well.
尝试了一些简单的方法,例如:
Tried something simple like:
function reverseArray(array) { for (var i = 0; i < array.length; i++) { // var elem = array.shift(); var elem = array.shift() array.push(elem) } return array } array = ['a', 'b','c','d','e']; reverseArray(array);
但这并不能真正改变它。有关如何执行此操作的任何建议或解释?
But that doesn't really change it. Any advice or explanation on how to do this?
推荐答案使用ES6语法,您无需将值复制到临时文件中变量(最后一个需求是什么?)。
With ES6 syntax you don't need to copy a value into a temporary variable (is that what the last requirement is about?).
function reverse(arr) { for(let i = 0, j = arr.length-1; i < j; i++, j--) [arr[i], arr[j]] = [arr[j], arr[i]]; } const arr = ['a','b','c','d','e']; reverse(arr); console.log(arr);
有人可能会说在这里创建了数组(如果引擎没有对此进行优化),就像 splice 还会创建一个数组(作为其返回值)。
One may argue that arrays are created here (if engines don't optimise this away), just like splice also creates an array (as its return value).
更多推荐
反转数组而无需“反转”或复制数组
发布评论