何时未定义扩展阵列映射 [英] When Extending Array map is undefined

查看:71
本文介绍了何时未定义扩展阵列映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试扩展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.

我遇到的问题是该地图未定义。我显然可以解决这个问题,但我不明白为什么我要扩展数组,因此应该有它的功能?

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.

推荐答案

使用

constructor(items) {
    console.log(...arguments);
    super(...items);
}

可能会对此有所了解。在 map 中,创建一个类型为 Array2 的新数组 - 它正在调用具有所需长度的构造函数, 4 - 就像标准的数组一样。但是,您正在将参数 items 传播到超级调用中,该调用将尝试迭代值 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。或者简单地省略构造函数,因为默认构造函数将为您执行此传递。

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

这是来自是为。

这篇关于何时未定义扩展阵列映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆