2

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?

Josh Weinstein
  • 2,788
  • 2
  • 21
  • 38

3 Answers3

3

for ... in loops loop over the keys of the object specified in after in. The keys of your array are 0, 1, 2 (arrays are objects with key value pairs).

Isaac Madwed
  • 986
  • 9
  • 23
2

for-in loops do not loop through the values of elements, it loops through the keys.

An array does have keys, using indexes, so what you get for each elem is the index.

A resource for you: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

TbWill4321
  • 8,626
  • 3
  • 27
  • 25
1

This is because you are using an array. Arrays are just objects whose keys are indices.

i.e.

[9, 8, 7] => {0: 9, 1: 8, 2: 7}

Once you understand this implementation, you'll see that it is actually doing the right thing.

Toby Liu
  • 1,267
  • 9
  • 14