Steven Scott
Steven Scott

Reputation: 11250

Typescript Structure array length not working

I have a class with an internal structure that is an array of a structure that I have:

Fields: DataField<any>[] = new Array<DataField<any>>(); 

I then have a function that adds the structure into the array with the key from the structure used as an index.

AddField(FieldInfo:DataField<any>):void {
    let FieldName:string = FieldInfo.Name;
    this.Fields[FieldName] = FieldInfo;
}

In trying to test that this works, I can see that the structure is created properly, but the length value is not returning correctly. Console.log output:

console.log(TestObject.Fields);
  [ Name: DataField { Name_: 'Name', Size_: 32, Value_: 'My Name' },
    Age: DataField { Name_: 'Age', Size_: 2, Value_: 33 } ]

My test is then:

expect(TestObject.Fields.length).toBe(2);

But this test fails and reports the length is 0.

expect(received).toBe(expected)
Expected value to be (using ===):
  2
Received:
  0

Using the console.log on the TestObject.Fields.length shows 0 as well.

console.log(TestObject.Fields.length) 
  0

Upvotes: 0

Views: 1552

Answers (1)

basarat
basarat

Reputation: 275917

Setting an element by index doesn't change the length:

enter image description here

Fix

Use methods like push slice etc that exist on arrays.

Upvotes: 1

Related Questions