简体   繁体   English

JS Array.prototype.filter与Array扩展类构造函数调用

[英]JS Array.prototype.filter with Array extending class constructor call

I have a Array extending class A which I want to filter. 我有一个数组扩展类A我想过滤。 It seems like the constructor gets called another time with just 0 as parameter. 似乎构造函数被调用另一次只有0作为参数。 Why is that? 这是为什么?

Here is an example showing the problem: 这是一个显示问题的示例:

class A extends Array {
   constructor(...a){
      console.log(a)
      super(...a);
   }
}

let a = new A("ok", "long");

let b = a.filter((e) => {
   return e.length === 4;
});

console.log(b);

Which logs: 哪些日志:

[
    "ok",
    "long"
]
[
    0
]
[
    "long"
]

Where is the 0 comming from? 0来自哪里?

Array.prototype.filter is returning a new (array) value. Array.prototype.filter返回一个新的(数组)值。 That value needs to be of the same "type" as the original array, ie it has to be an instance of your class. 该值必须与原始数组具有相同的“类型”,即它必须是您的类的实例。

.filter creates a new empty instance of your class: .filter创建一个新的类的空实例:

1. Let O be ? O成为? ToObject ( this value). ToObject值)。
[...] [...]
5. Let A be ? A成为? ArraySpeciesCreate ( O , 0). ArraySpeciesCreateO ,0)。
[...] [...]

https://www.ecma-international.org/ecma-262/9.0/index.html#sec-array.prototype.filter https://www.ecma-international.org/ecma-262/9.0/index.html#sec-array.prototype.filter

but why would it give me a 0 and not just no paramenter 但为什么它会给我一个0而不只是没有参数

Because the spec says that the new array is created by calling its constructor with (length) 0 as argument. 因为规范说新的数组是通过调用其构造函数(长度为0作为参数创建的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM