如何减少阵列?我的阵列没有返回
我正在尝试减少数组。
我的输出应该是 [1,5,4] 但它给了我一个空数组。
let arr=[1,[2,3],4]
let newarr=[]
let myarr=()=>{
for(i=0;i<3;i++){
array=arr[i].reduce
newarr.push(array)
return newarr
}
}
I am trying to get a reduced array.
My output is supposed to be [1,5,4] but it gives me an empty array.
let arr=[1,[2,3],4]
let newarr=[]
let myarr=()=>{
for(i=0;i<3;i++){
array=arr[i].reduce
newarr.push(array)
return newarr
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将一个函数传递给您的 array.reduce,而且您还必须实际调用您的函数,如下所示(console.log 调用它):
总是有更短、更漂亮的方法来做同样的事情,上面的解决方案是尽可能可读的以理解它,一行是:
You need to pass a function to your
array.reduce
,also you have to actually call your function,like so ( console.log calls it ):there are always shorter and prettier ways to do the same,above solution is as readable as possible to understand it,an one-liner would be :
Array#reduce 是一个数组方法,需要向其传递一个函数。此外,您还定义了一个函数,但没有调用它。
请尝试以下操作:
或者,您可以使用 Array#map 和 Array#reduce 方法,如下所示。在这两种情况下,技巧都是识别数组以便对其应用
reduce
:Array#reduce
is an array method and it needs a function to be passed to it. Also you have defined a function but you do not invoke it.Try the following:
Alternatively, you can use
Array#map
andArray#reduce
methods as follows. In both cases the trick is to identify the array so as to applyreduce
to it: