簡體   English   中英

如何在數組Javascript中向項目添加嵌套

[英]How to add nesting to an items in array Javascript

因此,如果我想從數組項目中刪除嵌套,我絕對可以做到:

var nestedArrs = [[1],[2],[3],[4],[5]];
var denestedArr = [].concat.apply([], nestedArrs);
console.log(denestedArr) //prints [1, 2, 3, 4, 5];

但是如果我需要倒退並添加嵌套怎么辦?

var unnestedArr = [7, 8, 9, 10];
var nestedArr = [] ? // Say I want to add nesting to every other item in arr
console.log(nestedArr); //so I wanted it to print [[7], 8, [9], 10]
//& nested Arr needs to be based upon the starting unnestedArr.

 var unnestedArr = [7, 8, 9, 10]; var nestedArr = unnestedArr.map(function(item, index) { return index % 2 === 0 ? [ item ] : item; }); console.log(nestedArr); 

Andreas答案類似,我建議使用.map進行函數編程 如果您不喜歡對“其他”決策標准進行“硬編碼”,則可以制作一個“掩碼”

 const unnestedArr = [7, 8, 9, 10]; // Here we define which items should be nested const isEven = x => x % 2 === 0; const nestCriterion = (item, index) => isEven(index); const shouldBeNested = unnestedArr.map(nestCriterion); // = [true, false, true, false]; // Next we perform the nesting to the items we identified above const nestedArr = unnestedArr.map((item, index) => { return shouldBeNested[index] ? [ item ] : item; }); // Alternatively, we could've just used "one big function" like this: const nestedArr2 = unnestedArr.map((item, index) => { if (index % 2 === 0) { return [ item ]; } else { return item; } }); // If we wanted to modify the array in place (instead of creating a new one) // we could've used .forEach instead of .map and modified (mutated) // elements of interest (eg by wrapping them in an array) console.log(unnestedArr, nestedArr, nestedArr2); 

這是jsbin.com上的實現

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM