0

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
2
  • try console.log(Object.keys(TestObject.Fields).length) Commented Nov 10, 2017 at 5:07
  • this.Fields[FieldName] = FieldInfo, you index a string into an array, do you even array bro? Commented Nov 10, 2017 at 5:08

1 Answer 1

1

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.

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

2 Comments

The reason x['a'] = 'a' does not change the length is because it just adds a as another property on array instance x, it does not update the underlying contiguous memory block that x points to, arrays are just javascript objects with numeric properties, and javascript allows you to add any properties to existing objects
@basarat I still want to be able to access the element by the key name as this code is from a library function that is building the array. If I use the push() onto the array, can I always count on the new entry being the last entry, so I can change the index to the key? I think I might be better to move this into a Dictionary object.

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.