为什么在Javascript中使用.push()无法直接返回值? [英] Why can't direcrlty return a value by using .push() in javascript?
本文介绍了为什么在Javascript中使用.push()无法直接返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下面的flatten函数为例,为什么我不能直接在累加器上使用 return
。 Push()
using below flatten function as example, why cant I use return
directly on the accumulator. Push()
function flatten(array){
return reduce(array,function(accumulator, value){
if(Array.isArray(value)){
each(value,function(value1){
return accumulator.push(value1); //as shown
})
}else{
return accumulator.push(value); //as shown
}
},[]);
};
相反,我需要在单独的行上返回累加器吗?
Instead, I need to return accumulator on a separate line?
function flatten(array){
return reduce(array,function(accumulator, value){
if(Array.isArray(value)){
each(value,function(value1){
accumulator.push(value1);
})
}else{
accumulator.push(value);
}
return accumulator //as shown
},[]);
};
但是如果使用诸如.concat()之类的方法,我将能够使用返回
...
but if use method such as .concat() I will be able to use return
on it...
推荐答案
推送
方法返回Array的新长度。
The push
method returns the new length of the Array.
concat
方法返回一个全新的数组,其中包含两个数组的组合。
The concat
method returns a brand new array containing a combination of the two arrays.
这篇关于为什么在Javascript中使用.push()无法直接返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文