admin管理员组文章数量:1332395
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?
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?
- 2 it is standard by arrays, which are exotic objects. – Nina Scholz Commented Dec 23, 2021 at 10:01
2 Answers
Reset to default 5Its 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 remend 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 e with many functions, like length
, sort
, find
etc that an object will not
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"
本文标签: javascriptIs it bad to have quotnumberquot as object keysStack Overflow
版权声明:本文标题:javascript - Is it bad to have "number" as object keys? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742277541a2445478.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论