我正在使用 typescript 在数组中添加新原型(prototype)。 我发现我可以在 for 循环中打印出原型(prototype)函数。
.ts
declare global {
interface Array<T> {
group(groupByKey: T): Array<T>;
}
}
if (!Array.prototype.group) {
Array.prototype.group= function<T>(this: T[], groupByKey: string): T[] {
return group(this, groupByKey);
};
}
控制台
var keys = Object.keys({a:1});
var str=""
for (var k in keys) {
console.log(k)
}
控制台输出为
0
group
是否可以打印出数组中的值而不是原型(prototype)值。 但原型(prototype)也可以很好地运行。
最佳答案
您看到函数名称是因为它被定义为可枚举属性。您可以更改定义方式来解决此问题:
Object.defineProperty(Array.prototype, "group", {
value: function<T>(this: T[], groupByKey: string): T[] {
return group(this, groupByKey);
},
enumerable: false, // <-- important part
configurable: true,
writable: true
});
关于javascript - 数组原型(prototype)将包含在数组列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53865941/