繁体   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