user11367277
user11367277

Reputation:

How to add elements in a Array?

I am trying to add elements in an Array in Typescrypt with the push method, but it does not seem to work. the array remains empty. This is my code:

         list: Array<int> = Array(10)
         for(let x = 0; x <= 10; x++) {
                    list.push(x)
         }

someone got the same problem?

Upvotes: 0

Views: 3078

Answers (3)

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

So a few things to note:

  • There's no int type in TypeScript, since JavaScript has only one number type, the corresponding TypeScript type is called number.
  • You shouldn't use Array(n) (or the array constructor in general) to create an array, there's a lot of information about why that is (primarily, it creates what's called a sparse array, with a length property but no elements), but you should generally use [] to create a new array. All arrays in JavaScript are dynamic anyway, so the 10 you pass has no meaning.
  • You should never define variables without declaring them with const, let or var.

Combining the points above, here's how your code should look like for this case

const list: number[] /* or Array<number> */ = []
for(let x = 0; x <= 10; x++) {
  list.push(x)
}

Upvotes: 2

Pac0
Pac0

Reputation: 23149

in your case you can do :

     list: Array<number> = [];
     for(let x = 0; x <= 10; x++) {
          list.push(x)
     }

or

     list: Array<number> = Array(10)
     for(let x = 0; x <= 10; x++) {
          list[x];
     }

Explanation on your error :

Array(10) already creates an array with 10 "empty" elements.

if you use push on it, you will actually get your elements pushed, but in the 11th to the 20th position.

The 1st to the 10th ranks stay empty (and will return undefined if you try to get their value them)

Upvotes: 2

MohanaRajesh
MohanaRajesh

Reputation: 51

int type is not available in typescript use number instead of int

let list: Array<number> =  Array(10);
for (let x = 0; x <= 10; x++) {
  list.push(x)
}

above code is pushing the value to array but this will return

[undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

to fix this please change code to

let list: Array<number> =  Array();
for (let x = 0; x <= 10; x++) {
  list[x] = x;
}

this will return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Upvotes: 1

Related Questions