So I am trying to implement an object as a set in javascript, where there are no duplicate elements or specific order of elements in the collection. Here is my implementation with the regular for loop:
var Set = function(elements) {
for(i=0;i<elements.length;i++) {
this[elements[i]] = true;
}
};
And this works as intended:
y = new Set([4, 5, 6, 3, 2])
=> { '2': true, '3': true, '4': true, '5': true, '6': true }
However, if I used the for in loop, something really strange happens:
var Set = function(elements) {
for(var elem in elements) {
this[elem] = true;
}
};
t = new Set([9, 8, 7])
=> { '0': true, '1': true, '2': true }
Why does the for in loop cause the elements 0, 1, and 2 to be in my set, and not the numbers I had in my array originally?