[英]Stop Object.keys from iterating over custom global methods?
我已經為通常在代碼中使用的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,這會導致相同的問題。
我如何只循環打字稿中的六個元素?
您可以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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.