TypeScript Set<>集合通过索引

时间:2017-06-15 09:14:17

标签: typescript collections set

大家好,我是TypeScript的新手,也许我看不到明显的东西,但这是我的问题:

const someSet = new Set();
someSet.add(1)
console.log(someSet[0])

给我未定义可以有人解释我为什么我们不能通过索引获得价值?我怎么能这样做?

3 个答案:

答案 0 :(得分:4)

Set is part of ES6, not TypeScript. It's property is to be an iterable collection of unique values though not with a fixed index. Do not rely on indices to access these items since they're not ordered (use an Array instead). If you would like to iterate over a set you can always use someSet.forEach().

答案 1 :(得分:2)

You need to use an iterator:

var iterator = someSet.values();
console.log(iterator.next().value);

You can learn more here.

TypeScript doesn't throw when you do someSet[0] because you can also access the properties using the index syntax:

someSet["values"]

答案 2 :(得分:0)

Probably because Set does not have indexer.

You can get value by doing so:

let val = [...mySet][0];