如何“重复"一个数组n次

编程入门 行业动态 更新时间:2024-10-20 03:48:05
本文介绍了如何“重复"一个数组n次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在python中,您可以执行以下操作:

In python you can do:

arr = [1,2,3] * 3 print(arr)

输出:

[1,2,3,1,2,3,1,2,3]

在Java脚本中是否有一种简洁的方法?我能想到的最好的是这样的:

Is there a concise way of doing this in java script? The best I can think of is something like:

let arr2 = [...arr, ...arr, ...arr]

但是如果我想做100次,那将是不切实际的.在python中,我会将其乘以100.

but if I wanted to do this 100 times it would be impractical. In python I would just multiply it by 100.

推荐答案

您可以执行以下操作:

var repeated = [].concat(... new Array(100).fill([1, 2, 3]));

这将创建一个给定长度的数组(此处为100),并用要重复的数组填充它([1, 2, 3]).然后将该数组作为参数列表传播到[].concat().

That creates an array of a given length (100 here) and fills it with the array to be repeated ([1, 2, 3]). That array is then spread as the argument list to [].concat().

哦,等一下

var repeated = new Array(100).fill([1, 2, 3]).flat();

会短一些.

更多推荐

如何“重复"一个数组n次

本文发布于:2023-11-30 20:50:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651432.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!