简体   繁体   English

如何在Javascript / ES6中获得这样的输出

[英]How to get output like this in Javascript/ES6

Let's say you have an array like this: 假设您有一个像这样的数组:

//Input [1,2,3,4,5,6,7] //输入[1,2,3,4,5,6,7]

How to write the function which will get us the output of 如何编写函数以获取输出

//Output //输出

 Array1 = [1]
 Array2 = [1,2]
 Array3 = [1,2,3]
 Array4 = [1,2,3,4]
 Array5 = [1,2,3,4,5]

And

//Output 1. [1,1,2,1,2,3,1,2,3,4...] //输出1. [1,1,2,1,2,3,1,2,3,4...]

// tried this //尝试过

for (i = 0; i < arr.length; i++) { 
    arr = new Array(arr[i]);
}

You can use functions like Array#map and Array#slice to easily create the first function, and use Array#concat with spread syntax to flatten a 2D array. 您可以使用Array#mapArray#slice之类的函数轻松创建第一个函数,并使用具有扩展语法的 Array#concat展平2D数组。

 function prefixes(array) { return array.map((_, index) => array.slice(0, index + 1)); } function flatten(array) { return [].concat(...array); } const output = prefixes([1,2,3,4,5,6,7]); console.log(output); console.log(flatten(output)); 

You could reduce the array by slicing the wanted part with spread syntax ... . 您可以通过切片与希望部分减少阵列蔓延语法...

 var array = [1, 2, 3, 4, 5, 6, 7], result = array.reduce((r, _, i, a) => [...r, ...a.slice(0, i + 1)], []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Use forEach and for loop 使用forEach和for循环

 var arr = [1, 2, 3, 4, 5, 6, 7]; var arrys = []; //lopping over the array, and creating the new array and putting values // equal to number of index arr.forEach(function(item, index) { var tempArray = []; for (var m = 0; m <= index; m++) { tempArray.push(arr[m]) } arrys.push(tempArray) }) console.log(arrys) // flat the previously created array var flatten = []; arrys.forEach(function(item) { item.forEach(function(item2) { flatten.push(item2) }) }) console.log(flatten) 

You can do this simply by using two nested for loops like this, 您只需使用两个嵌套的for循环即可完成此操作,

 let arr = [1, 2, 3, 4, 5, 6, 7]; function foo(arr) { let rarr = [];//result array for (let i = 0; i < arr.length; i++) { let a = [];//array[i] for (let j = 0; j <= i; j++) { a.push(arr[j]); } rarr.push(a); } return rarr; } console.log(foo(arr)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM