简体   繁体   English

js减少只有空值的数组

[英]js reduce of an array with only empty values

Why doesn't this iterate? 为什么不迭代呢?

(Array(5)).reduce(function(cur,prv,n,a){alert(n)},'');

I never reached the function body, seemingly ignoring all of the empty values, which is not what I want it to do. 我从未到达过函数主体,似乎忽略了所有空值,这不是我想要的。

As far as I understand Array(5) returns an instance of Array Object with a property length (value 5), but without values. 据我了解, Array(5)返回具有属性length (值5)但没有值的Array Object的实例。 One way to be able to use reduce (or other array methods like map ) here is: 在此处可以使用reduce (或其他数组方法,例如map )的一种方法是:

String(Array(5)).split(',').reduce(function (cur, prv, n, a) { /* ... */ })

An alternative could be: 替代方法可以是:

Array.apply(null,{length: 5}).map( [callback] );
// or
Array.apply(null,Array(5)).map( [callback] );

But that will encounter a maximum call stack error at some point. 但这在某个时刻遇到最大调用堆栈错误。 The string/split method keeps working (albeit a bit slower) for large arrays. 字符串/拆分方法对于大型数组仍然有效(尽管速度稍慢)。 Using node.js on my (not so fast) computer mapping Array(1000000) with the string/split-method lasts 0.47 seconds, the array.apply method for the same crashes with a RangeError ( Maximum call stack size exceeded ). 在我的(不是那么快)计算机映射Array(1000000)使用string / split-method持续时间为0.47秒时,使用node.js时,相同的array.apply方法崩溃时会发生RangeError超出最大调用堆栈大小 )。

You can also write a 'static' Array method to create an Array with n values and all usable/applicable Array methods in place: 您还可以编写“静态” Array方法来创建具有n个值的Array ,并使用所有可用/适用的Array方法:

Array.create = function (n, mapCB, method, initial) {
  method = method in [] ? method : 'map';
  var nwArr = ( function(nn){ while (nn--) this.push(undefined); return this; } )
                .call([], n);
  return mapCB ? nwArr[method](mapCB, initial) : nwArr;
};
// usages
Array.create(5, [callback], 'reduce', '');
Array.create(5).reduce( [callback], '');
Array.create(5).map( [callback] ).reduce( [callback] );
// etc.

As others have stated, the implementation of reduce causes this to throw a TypeError because the calling array has no initial values. 正如其他人所述,reduce的实现会导致抛出TypeError,因为调用数组没有初始值。 To initialize an array with initial values of undefined and successfully invoke the function, try something like this: 要使用未定义的初始值初始化数组并成功调用该函数,请尝试如下操作:

Array.apply(undefined, Array(5)).reduce(function(cur,prv,n,a){alert(n)},'');

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

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