The case is:
function trocaPrimeiroEUltimo(array) {
array.array[0]
array.array[array.length - 1]
return array
}
I did this way, but it didn't work. I can't change the structure of the function, just what it's inside. Someone, could please help me?
CodePudding user response:
Do you want to replace the last value with the first value? if so, do:
temp = array[0]
array[0] = array[array.length-1]
array[array.length-1] = temp
That's a simple swap.
CodePudding user response:
The syntax makes use of new ES6 capabilities (destructuring an array). This way the exchange can be done without a temporary variable.
The whole thing can even be done as a one-liner:
const arr=[7,8,9,10,11];
const swapFirstLast=(a,l)=>([a[0],a[l]]=[a[l=a.length-1],a[0]],a);
console.log(swapFirstLast(arr))
The use of the argument l
is also something you probably would not do in a "real" application. I only went for it so I would not have to define the variable locally. l
is assigned a value on the right hand side of the assignment expression. By the time the result needs to be stored l
has been calculated and can also be used for addressing the right target element.