How to insert values into an empty array?

Asked

Viewed 461 times

-3

for example : var arr = [] . How to insert elements into this empty array? I tried many more unsuccessfully. I tried to do it more dynamically without success.

  • 1

    What have you tried to do? Edit your reply by adding a minimal, complete and verifiable example.

  • Basically. How to add values in an empty array through loops

1 answer

3

Hello,

There are several ways to do this in Javascript.

You can use the method push, adding elements at the end of its vector.

Thus:

arr.push(1); or arr.push({ nome: 'Lucas', sobrenome: 'Bittencourt' }); (contrary to the method pop, that removes elements from the end of its vector)

Or you can use the method unshift adding elements at the beginning of its vector.

Thus:

arr.unshift(1); or arr.unshift({ nome: 'Lucas', sobrenome: 'Bittencourt' }); (contrary to the method shift, which removes elements from the beginning of its vector)

Or you can do it:

const arr = []

arr[arr.length] = 1;
arr[arr.length] = 2;

This will result in [1, 2]

Or you can use the methods splice or concat. Anyway, there are many possibilities :)

  • Thanks man. I know this method(push) but it didn’t even cross my mind.

Browser other questions tagged

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