Why item in Set is called value instead of key in

2020-03-31 07:39发布

Set.prototype.forEach which accepts a callback function in ES6 The function has 3 parameters to be consistent with Map.prototype.forEach. MDN says both the first 2 parameters for the callback are values because there is no keys in Set object. Why the item in Set is considered as value instead of key? No duplicated key in Set object would make more sense because there is also no duplicated key in Map.

Another aspect that value in Set looks like key in Map is that it makes Set.prototype.has(value) and Map.prototype.has(key) more consistent. Duplicated keys are NOT allowed in Array (key is index) and Map, but this cannot be extended to Set which doesn't allow duplicated values. Make it as duplicated keys are not allowed in all containers might be a more succinct rule.

2条回答
姐就是有狂的资本
2楼-- · 2020-03-31 08:15

It's just because the semantics of set collections. A set stores values while a map stores keys and values.

For example, both motorbikes and bicycles own two wheels, but you still say that there're motorbikes and bicycles. Just because set values and map keys are unique doesn't mean that they're the same thing.

查看更多
贼婆χ
3楼-- · 2020-03-31 08:16

From the MDN link which you have attached.

The are no keys in Set objects. However, the first two arguments are both values contained in the Set, so that the callback function is consistent with the forEach methods for Map and Array.

We can say that set is just an array which keeps distinct elements. There are no keys in sets.

查看更多
登录 后发表回答