当扩展数组映射未定义时 [英] When Extending Array map is undefined
问题描述
我正在尝试扩展 Array,以便我可以添加自己的附加功能.我已经读到扩展 Array.prototype 可能很危险,所以我试图通过类继承以正确的方式做到这一点.
I'm trying to extend Array so that I can add in my own additional functionality. I've read that extending Array.prototype can be dangerous, so I am trying to do it the correct way with class inheritance.
我遇到的问题是地图未定义.我显然可以解决这个问题,但我不明白为什么我要扩展 Array 并因此应该具有它的功能?
The issue I'm running into is that map is undefined. I can obviously work around this but I don't understand why as I am extending Array and therefore should have It's functionality?
export default class Array2 extends Array {
constructor(items) {
super(...items);
}
addOne() {
return this.map((x)=>{
return x+1;
})
}
}
let arry2 = new Array2 ([9, 1, 4, 0]).addOne();
console.log(arry2);
我希望 Array2 (4) [10, 2, 5, 1] 登录到控制台,但我收到以下错误.
I expect to have Array2 (4) [10, 2, 5, 1] logged into the console but instead i get the following error thrown.
Uncaught TypeError: undefined is not a function
编辑删除构造函数似乎解决了这个问题,但没有解释为什么当构造函数存在时它会失败.特别是当构造函数只是调用 super 时.
Edit Removing the constructor seems to fix the issue but does not explain why it fails when a constructor is present. especially when the constructor is just calling super.
推荐答案
Debugging with
Debugging with
constructor(items) {
console.log(...arguments);
super(...items);
}
可能会对此有所了解.在 map
中,创建了一个类型为 Array2
的新数组 - 它正在调用具有所需长度的构造函数,4
- 就像标准 Array
将支持这一点.但是,您将参数 items
传播到 super 调用中,该调用将尝试迭代值 4
- 显然它不可迭代,失败并显示4[Symbol.iterator]()
不是函数"(好吧,这就是消息应该是什么.
may shed some light on this. In map
, a new array is created, of type Array2
- and it is calling the constructor with the desired length, 4
- just like a standard Array
would support this. However, you are spreading the argument items
into the super call, which will try to iterate the value 4
- and clearly it's not iterable, failing with "4[Symbol.iterator]()
is not a function" (ok, that's what the message should have been).
为避免这种情况,请使用标准构造函数签名并将任何参数按原样直接传递给 super.或者干脆省略 constructor
,因为默认的构造函数会为你做这个传递.
To avoid this, use the standard constructor signature and just pass any arguments directly to super as they are. Or simply omit the constructor
, as the default constructor will do this pass-through for you.
使用
export default class Array2 extends Array {
addOne() {
return this.map((x)=>{
return x+1;
})
}
}
const array2 = Array2.from([9, 1, 4, 0]).addOne();
const array3 = Array2.of(9, 1, 4, 0).addOne();
console.log(array2, array3);
这就是 of
和 from
的用途.
That's what of
and from
were made for.
这篇关于当扩展数组映射未定义时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!