阻止Object.keys遍历自定义全局方法?

时间:2018-09-24 11:16:49

标签: javascript typescript

我为 typescript 数组类型添加了一种方法,该方法通常在代码中使用,例如:

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);    
}

但是,在代码的其他地方,我有一个希望循环遍历的6个元素组成的数组,但是扩展方法随这些元素一起返回,例如:

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

}

我也尝试过getOwnPropertyNames,这会导致相同的问题。

如何只遍历 typescript 中的六个元素?

1 个答案:

答案 0 :(得分:0)

您可以使用for of

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

For of仅发出一个for循环,因此避免使用Object.keys()

如果您确实要使用Object.keys,则需要修改Array.prototype将该属性标记为不可枚举。

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);
  }
});

甚至更好的是,停止使用您的自定义扩展,而仅使用带有扩展的推送

代替

 myArray.extend(arr);

你可以

 myArray.push(...arr)