简体   繁体   中英

Stop Object.keys from iterating over custom global methods?

I have added a method to the typescript array type that I usually use in the code like eg:

declare global {
    interface Array<T> {
        extend(other_array : T[]) : void;
    } }

Array.prototype.extend = function (other_array : Array<any>) {
    other_array.forEach(function(v) {this.push(v)}, this);    
}

However, elsewhere in the code I have an array of 6 elements that I wish to loop through, but the extended method is returned with the elements, eg:

for(let i in Object.keys(days)) {
      let d = days[i];

}

I have also tried getOwnPropertyNames, which results in the same issue.

How can I loop only over the six elements in typescript ?

You can use for of

for(let d of days) {
  // d  is defined here
}

For of just emits a for loop so it avoids using Object.keys()

If you really want to use Object.keys , you need to modify Array.prototype marking that property as not enumerable.

Object.defineProperty(Array.prototype, 'extend', {
  enumerable: false,
  configurable: false,
  writable: false,
  value: function (other_array: Array < any > ) {
    other_array.forEach(function(v) {
      this.push(v)
    }, this);
  }
});

Or even better, stop using your custom extend and just use push with spread

Instead of

 myArray.extend(arr);

You can do

 myArray.push(...arr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM