[英]How can i write the following code without for loops in javascript
I need help with the following program in javascript我需要 javascript 中以下程序的帮助
A function, written without any loop statements, that accepts an array and produces a new array equal to the initial array with ith element (1-based) repeated i times.一个 function,编写时没有任何循环语句,它接受一个数组并生成一个与初始数组相等的新数组,其中第 i 个元素(基于 1)重复 i 次。
i was able to write the code in for loop, just need help in writing without loop我能够在for循环中编写代码,只需要帮助编写没有循环
export function stretched(a) {
const stretchedArray = [];
for (let [index, item] of a.entries()) {
for (let i = 0; i < index + 1; i++) {
stretchedArray.push(item);
}
}
return stretchedArray;
}
This can be another approach:这可以是另一种方法:
function stretched(a) { const stretchedArray = []; for (let [index, item] of a.entries()) { stretchedArray.push(...(new Array(index + 1).fill(item))) } return stretchedArray; } console.log(stretched(['a','b','c']))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.