0

I have a following indexable object declared which will contain list of Video Models identified by some key which is a number.

component.ts

private videoItems : {[key: number]: Array<Video>};      // indexable object

constructor(private action: Action, private videoModel: Video) {}

And I have assigned it in the following way in component

this.action.items.forEach(
            (item : Video) => {
                this.videoItems[item.idVideo] = Object.assign(new Video(),this.videoModel);
            }
        );

Video.model.ts

export class Video {

    private _idVideo : number;

    get idVideo (): number {
        return this._idVideo ;
    }

    set idVideo (value: number) {
        this._idVideo = value;
    }
}

If I try to access the videoItems like this.videoItems[12], I get undefined. Where as I if I access it like this.videoItems['12'] I get the video object properly. My question is even though I have declared the key as number and is also set with a number, then why should I access it using a string?

1
  • 1
    that's not a typed array, it's an indexable object. it behaves like an object. :) Commented Jun 28, 2017 at 7:17

1 Answer 1

1

Keys for JavaScript objects must be strings or symbols. The latter is a recent addition. Numbers are coerced to strings, so code like this works:

let x = {}
x[10] = 'foo';
console.log(x[10]); // Prints "foo"
console.log(x['10']); // Prints "foo"
x['20'] = 'bar';
console.log(x[20]); // Prints "bar"

Try it out in the browser or node and see that it does indeed behave that way. It's quite strange that it does not in your case. Perhaps there's something else going on?

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

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.