[英]How to get output like this in Javascript/ES6
假設您有一個像這樣的數組:
//輸入[1,2,3,4,5,6,7]
如何編寫函數以獲取輸出
//輸出
Array1 = [1]
Array2 = [1,2]
Array3 = [1,2,3]
Array4 = [1,2,3,4]
Array5 = [1,2,3,4,5]
和
//輸出1. [1,1,2,1,2,3,1,2,3,4...]
//嘗試過
for (i = 0; i < arr.length; i++) {
arr = new Array(arr[i]);
}
您可以使用Array#map
和Array#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));
您可以通過切片與希望部分減少陣列蔓延語法...
。
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; }
使用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)
您只需使用兩個嵌套的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.