[英]Javascript Function Not Flattening Array Properly
我整理了一個JavaScript函數,該函數應該可以平鋪嵌套數組。 但是,此方法始終只返回原始數組。 例如,使用以下數組[1, 2, 3, [4, 5, [6], [ ] ] ]
運行此函數只會返回該數組。 我知道可以通過reduce來做到這一點,但是什么邏輯原因在阻止這種方法的工作呢? .map
應該允許我操縱一個返回值,並通過遞歸調用在新數組中返回它。
function mapper(array) {
return array.map((item) => {
return (Array.isArray(item)) ? mapper(item) : item
}
)}
您正在將數組映射到自身。 基本上是因為map將返回一個數組,該數組具有與輸入完全相同的元素數。 您不能期望它返回更多,所以您不能使用它來展平數組。
應該使用reduce代替:
function flatten(obj) {
if (Array.isArray(obj)) {
return obj.reduce((a, b) => a.concat(flatten(b)), []);
} else {
return [obj];
}
}
是什么邏輯原因導致此方法無法正常工作?
var m = [1, 2, 3, [4, 5, [6], []]];
function mapper(array) {
return array.map((item) => {
// for 1,2,3 it will return item
// when it sees an array it will again call mapper & map
// function will return a new array from it, so map on
// [4, 5, [6], []] will return a new array but will not take out
// individual element and will put it in previous array
return (Array.isArray(item)) ? mapper(item) : item
}
)}
mapper(m)
map函數不會更改原始數組,但會返回一個新數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.