Jump to content

Merge Arrays with for loop


tscarq
Go to solution Solved by tscarq,

Recommended Posts

tenho um exercício para fazer com este enunciado:

Using the methods you have learned, modify the xMen array already declared in the editor so that only members of the X-Men are present.

Then add all of the mutants present in the xMen array to the freelancers array.

 

Já escrevi este código:

var xMen = ['Professor X', 'Cyclops', 'Beast', 'Iron-Man', 'Hobgoblin'];
var freelancers = ['Legion', 'Magneto'];

xMen.pop();
xMen.pop();

for(var i=0; i<freelancers.length; i++) {
    
    freelancers.push(...xMen);    
    
    freelancers.length = 5;

        console.log(freelancers[i]);
}

O código que escrevi está de facto a imprimir o array freelancers + os primeiros 3 elementos do array xMen conforme pedido(acho que compreendi correctamente o enunciado) . No entanto aparece-me mensagens de erro a dizer:

>>>>Code is incorrect. You should use the first expression of the for loop to declare a variable.

>>>>Code is incorrect. The for loop should iterate until the value stored in i reaches the length of the array.

Alguém me consegue ajudar? obrigada

Link to comment
Share on other sites

  • Solution

Finalmente resolvido!!

var xMen = ['Professor X', 'Cyclops', 'Beast', 'Iron-Man', 'Hobgoblin'];
var freelancers = ['Legion', 'Magneto'];

xMen.pop();
xMen.pop();

for(var i=0; i<xMen.length; i++) {
    
    freelancers.push(xMen[i]);    
}

console.log(freelancers);
    
eu tinha que limitar a repetação do x.Men antes de o inserir no freelancers    

Link to comment
Share on other sites

  • 1 year later...
  • 3 weeks later...
Em 06/10/2022 às 02:02, Fernando Correia Junior disse:

Pode parecer bobo, mas explique-me essa linha freelancers.push(xMen[i]);
Não consigo perceber esse i ...

Significa o seguinte:

array.push = adicionar ao array  => https://www.w3schools.com/jsref/jsref_push.asp
Um array começa no index 0, ao fazer o loop for i=0 para tamanho do array xmen adiciona ao array freelancer o valor de cada index do xmen

 

You can't do it, kid. But don't worry, my boy. You're not the only one. No one else can do it.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.