0

I implemented a simpel feature:

/**
 * Expects to be an array of numbers.
 * @param value <number>
 * @returns {number}
 */
Array.prototype.nextHigherNumber = function(value) {
    var length = this.length;
    if(length < 1) {
        return value;
    }
    var self = this;
    var returnValue = null;
    for (var i = 0; i < length; i++) {
        var current = self[i];
        if (current > value
            && (returnValue === null || returnValue - value > current - value)) {
            returnValue = current;
        }
    }

    return returnValue === null ? value : returnValue;
};

It works quite well.

The issue: In an other part of project is this construct used

// in this case "myArray" = []; // empty array
for(var value in myArray) {
  // stuff
  console.log('value',value);
}

The first output of "value" is "nextHigherNumber". So i assume this Iterator goes not only over values but over methods to. I xpect i don't find me inside of this itteration. So my Questions:

1) Why?

2) And can i prevent somehow methods to be iterated as well?

I know, workarount is to use this feature just not as prototype on Array. But it works not as expected. I must overlooking something..

Desian
  • 1

1 Answers1

0

1) Why?

Because you added it as an enumerable property. You shouldn't iterate arrays with for..in though.

2) And can i prevent somehow methods to be iterated as well?

Sure, make it non-enumerable:

  Object.defineProperty(Array.prototype, "nextHigherNumber", {
    value(value) {
      //...
    },
    enumerable: false,
 });
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151