并发数组功能
我有一个功能,该功能采用一个包含数字字符串的子阵列,并返回每个子阵列中数字最高的数组:
const largestOfFour = arr => {
arr.map(e => {
e.sort((a,b) => b - a).splice(1);
});
return arr.flat();
}
它以上面格式的方式完美地工作,但是如果与并发进行格式化,它不起作用在传递的数组上的函数。像这样:
const largestOfFour = arr => {
return arr.map(e => {
e.sort((a,b) => b - a).splice(1);
}).flat();
}
以这种格式返回适当长度的数组,但每个元素都是null。谁能帮我理解为什么这是吗?我通常不会在阵列上链接并发功能问题。
I have a function that takes an array of sub-arrays containing number strings and returns an array with the highest number from each sub-array:
const largestOfFour = arr => {
arr.map(e => {
e.sort((a,b) => b - a).splice(1);
});
return arr.flat();
}
It works perfectly in the way it is formatted above but it does not work if it is formatted with concurrent functions on the array passed in. Like this:
const largestOfFour = arr => {
return arr.map(e => {
e.sort((a,b) => b - a).splice(1);
}).flat();
}
In that format it returns an array of appropriate length but each element is null. Can anyone help me understand why that is? I usually don't have a problem chaining concurrent functions onto an array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JavaScript中没有并发。但是您的
MAP
回调不会返回任何内容(语句块中没有return
)SO.map()
返回一个未定义值的数组。为避免原始数据被突变,我还将避免在原始数组上使用
sort
,并使用slice
而不是splice> splice
。但是,由于您只需要一个从每个数组中的值,您甚至都不需要
slice
:只需在index 0处获取值(制作flat
不必要):甚至更好,只需使用
Math.max
,这也使转换为数字:There is no concurrency in JavaScript. But your
map
callback does not return anything (there is noreturn
in the statement block) so.map()
returns an array of undefined values.To avoid that the original data gets mutated, I would also avoid the use of
sort
on the original array, and useslice
instead ofsplice
.But as you only need one value from each array, you don't even need
slice
: just get the value at index 0 (makingflat
unnecessary):Or even better, just use
Math.max
, which also makes the conversion to number:内部块(在地图中)没有返回任何东西,导致了一系列未定义的。固定在片段中...
The inner block (in map) issn't returning anything, resulting in an array of undefined. Fixed in the snippet...