Fix an Error - Javascript

Asked

Viewed 122 times

1

I’m doing a Javascript programming course and I can’t solve a question.

Follows the Statement.

Declare a function called "move", which takes two arrays, removes the last element of the first and adds it to the second.

Example:

var umArray = [1, 2, 3];

var outroArray = [4, 5];

mover(umArray, outroArray);

umArray //deveria ser [1, 2]

outroArray //deveria ser [4, 5, 3]

My Answer

function mover (umArray,outroArray){

var umArray = [1, 2,3];

var outroArray = [4,5];

umArray.pop()

outroArray.push(2)

}

Mistakes:

The move function([1,2],[3,4]) must modify the first matrix so that its value is [1] and modify the second one so that its value is [3,4,2]

1 answer

3


There are some errors in its function:

  • You redeclared the parameters umArray and outroArray with fixed values within the function:
    var umArray = [1, 2,3];
    var outroArray = [4,5];

This is incorrect, you receive these values per parameter, so you can delete this.

  • You used the methods push and pop, correct, but when the method pop is used, it removes and returns the value, and this value should be used as parameter in the push, but you did not use the return of pop and fixed the amount sent to push:

outroArray.push(2)


See an example of your code with the suggested fixes:

function mover (umArray,outroArray){
  const valor = umArray.pop();
  outroArray.push(valor);
}

var umArray = [1, 2, 3];
var outroArray = [4, 5];

mover(umArray, outroArray);

console.log(umArray); //deveria ser [1, 2]
console.log(outroArray); //deveria ser [4, 5, 3]


As the method pop returns the value and is the value that will be sent to the method push, you can do all this process in just one line, using the return method pop as a parameter in the method push:

function mover (umArray,outroArray){
  outroArray.push(umArray.pop());
}

var umArray = [1, 2, 3];
var outroArray = [4, 5];

mover(umArray, outroArray);

console.log(umArray); //deveria ser [1, 2]
console.log(outroArray); //deveria ser [4, 5, 3]


Documentations:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

  • 1

    Daniel, Thank you very much, your reply helped me a lot. Thank you very much for the strength.

  • Good evening Augusto, I am new at Stackoverflow, I did not locate the location to mark the resolution that was presented to me by Daniel. Could you show me the way please?

  • @Augustovasques, thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.