简体   繁体   English

如何在 javascript 中编写没有 for 循环的以下代码

[英]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.

相关问题 我如何在不使用JavaScript的任何循环的情况下搜索元素 - How can i search for an element without using any loops in javascript 我怎么能用javascript(没有jquery)写这个 - how can i write this with javascript (without jquery) 如何用JavaScript编写此PHP代码 - How can I write this PHP code in JavaScript 我该如何编写这个 javascript 代码清理器? - How can I write this javascript code cleaner? 如何修复以下javascript代码以使其与flowtype一起使用? - How can I fix the following javascript code to make it work with flowtype? 如何将以下常规 JavaScript 代码转换为 VueJS? - How can I convert my following regular JavaScript code to VueJS? 如何在javascript中设置图片链接??? 在以下代码中 - how can i set link to image in javascript??? in the following code 如何将以下JavaScript Promise转换为常规的异步代码? - How can I convert the following JavaScript Promise into regular asychronous code? 如何使用以下JavaScript代码触发模式框? - How can I trigger modal boxes using the following javascript code? 如何在与Datepicker相同的输入字段中用Javascript编写可编辑的时间代码,但不使用Datetimepicker - How can I write a editable time code in Javascript in the same input field as Datepicker, but without using Datetimepicker
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM