因此,如果我想从数组项中删除嵌套,我绝对可以这样做:
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.
答案 0 :(得分:3)
var unnestedArr = [7, 8, 9, 10];
var nestedArr = unnestedArr.map(function(item, index) {
return index % 2 === 0 ? [ item ] : item;
});
console.log(nestedArr);
答案 1 :(得分:0)
与Andreas的answer类似,我建议使用function programming的.map
方法。
如果您不喜欢对“其他”决策标准进行“硬编码”,则可以进行"mask"。
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 (e.g. by wrapping them in an array)
console.log(unnestedArr, nestedArr, nestedArr2);
上的实现