简体   繁体   English

如何在打字稿中的对象作为地图中获取数字键?

[英]How to get keys as numbers in an object-as-a-map in typescript?

I am using objects as maps in typescript: 我在打字稿中使用对象作为地图:

const myMap: { [myKey: number]: string } = {};
myMap[42] = 'some string';

It works fine... 它工作正常......

console.log(myMap[42]); // => 'some string'

...until I try to get the keys in the map ...直到我试图获取地图中的键

for (let key of Object.keys(myMap)) {
  // key is a string, not a number
}

I guess this is because Javascript actually stores the keys as strings internally, but is there a way to get the keys as numbers? 我想这是因为Javascript实际上将密钥存储为内部字符串,但有没有办法将密钥作为数字?

I guess I could use a Map but I'm a little wary of its performances. 我想我可以使用Map但我对它的表现有点警惕。 Also, I would lose some compatibility... 另外,我会失去一些兼容性......

Well, iterating over the keys of an object is exactly what the for-in loop does. 好吧,迭代对象的键就是for-in循环所做的。 You just have to use parseInt on it: 你只需要在它上面使用parseInt

for (let key in myMap) {
    if(myMap.hasOwnProperty(key)) {
        console.log(parseInt(key)); // 42
        console.log(myMap[key]); // some string
    }
}

Actually, Javascript convert any Index Signature to string by implicitly call toString(). 实际上,Javascript通过隐式调用toString()将任何索引签名转换为字符串。

You can check it by simply call: 您只需致电即可查看:

console.log(myMap['42']); // => 'some string'

and it will still work. 它仍然有效。 so whatever key you get from Object.keys() will be string. 所以从Object.keys()得到的任何键都是字符串。
If you still want to use it as number, you can do: 如果您仍想将其用作数字,则可以执行以下操作:

for (let key of Object.keys(myMap)) {
  console.log(typeof +key,'would be a number')
  console.log(typeof key, 'would be a string')
}

You could use an array, but then it puts undefined into every index not used. 您可以使用数组,但它会将undefined放入未使用的每个索引中。 That makes iteration more challenging, and means it's impossible to purposefully add undefined to the "map" without losing it. 这使得迭代更具挑战性,并且意味着不可能有目的地将undefined添加到“地图”而不会丢失它。

 const myMap = []; myMap[42] = "some string"; // 42 commas, then "some string" console.log(myMap.join(',')); // just "some string", but you lose the 42. console.log(myMap.filter(e => typeof e !== "undefined").join(',')); // Something similar to Map.prototype.entries for (let a of myMap.reduce((arr, cur, idx) => typeof cur !== "undefined" ? [...arr, [idx, cur]] : arr, [])) { console.log(a); // [ 42, "some string" ] } // Of course, a Map does this natively const myTrueMap = new Map(); myTrueMap.set(42, "some string"); for (let e of myTrueMap.entries()) { console.log(e); // [ 42, "some string" ] } 

There are some polyfills for Map (eg, https://www.npmjs.com/package/es6-map , https://github.com/paulmillr/es6-shim ), but YMMV. Map有一些polyfill(例如, https //www.npmjs.com/package/es6-map,https ://github.com/paulmillr/es6-shim ),但YMMV。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM