0

The following is the code in typescript,

count: number;

this.count is accessed from html component.

console.log(this.count) gives me 5.

var arrObj:number[] = new Array(this.count)

console.log(arrObj.length);

Here the length of the array is always 1.

var arrObj:number[] = new Array(5)

console.log(arrObj.length);

Output: 5

var arrObj:number[] = new Array(this.count)

console.log(arrObj.length);

Output:1

Why is the global variable length is always 1?

2 Answers 2

0

An array can also be created using the Array object. The Array constructor can be passed.

you are initializing the array again and again... from the code that you've shared, when you do:

  • var arrObj:number[] = new Array(5)
  • you're initializing the array of size 5 in this case, which will all be undefined

and when you do...

  • var arrObj:number[] = new Array(1)
  • you're initializing the array with a single item, which will be undefined in this case

you should do this once var arrObj:number[] = [] and then push the value in the array by doing arrObj.push(yourValue)

demo on stackblitz

Sign up to request clarification or add additional context in comments.

1 Comment

va arrobj:number[ ] =new Array(5) i.e; the array construtor is used.So when i pass 5 it creates an array of size 5 i.e; the length of the array(arrobj.length) gives me 5.. but i pass a variable which is global (this.count) and contains a value equals to 5 i.e; var arrobj:number[]=new Array(this.count ) give me an arrobj.length =1. Why is it so??
0

'this' always works in scope and array constructor always accept static values it will never do eval(this.something), so when you pass 'this.count' it is passed as 1 undefined static value that is why it is becoming one length array(undefined being a static value in itself).
Also to be noted array constructor accepts only

  1. A numeric value that represents the size of the array or
  2. list of comma separated values.

    In your case if you need alternate solution then initialize array empty and then assign
    arrObj.length = this.count

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.