I just searched through SO and it looks like everybody agrees with the idea that JavaScript and TypeScript are not supporting using numbers as keys in an object directly. But somehow my fellow developer has used some objects with numeric keys in our Angular project which are working just fine as other objects. This is what they look like.
{
1: 1,
2: 0,
3: 2
}
And calling the value in a form like obj[2]
does not have a problem at the moment. Just wondering if it is the right way to do it, and how well this usage is supported?
CodePudding user response:
Its fine, as in - its legal, as its how arrays work, though one thing to watch out for is that arrays will ensure the key is incremental, starting at 0, whereas a numerical key in an object will not, and WILL be misleading for other developers when they cant understand why obj[1] doesnt always live beside obj[2] etc, and by that I mean the use of within loops etc and simply incrementing the index by one each time. So, personally i wouldnt recommend it due to it looking like an array, but it not actually being an array...
Side - If you are trying to mimic an array, but want an index starting at 1, just use an array as normal and have your code just handle the offset each time. Arrays come with many functions, like length
, sort
, find
etc that an object will not
CodePudding user response:
In javascript keys in object are string type and if you have obj[1]
it will automatically turn into obj['1']
but not the same in Map
const obj = {}
obj[1] = 'one';
console.log(obj[1]);
// output: "one"
console.log(obj['1']);
// output: "one"
obj['1'] = 'one string';
console.log(obj[1]);
// output: "one string"
console.log(obj['1']);
// output: "one string"
const map = new Map();
map.set(1, 'one');
map.set('1', 'one string');
console.log(map.get(1));
// output: "one"
console.log(map.get('1'));
// output: "one string"