如何新建一个有重复元素的数组

类似['a','b','c','d','e','a','b','c','a','b','c','a','b','c']这样的 有没有高级点的写法


慕神8447489
浏览 454回答 3
3回答

繁星点点滴滴

function getArr($count){$str = 'abc';$arr = array();for($i=0;$i<$count;$i++){&nbsp; &nbsp; $rand = rand(0,2);&nbsp; &nbsp; $arr[] = $str[$rand];}}$count为你想要新建的数组的个数,主要利用能通过下标获取字符串的某个字符

万千封印

function repeatArr(arr, len, start) {&nbsp; var ret = [];&nbsp; for (var i = start || 0; i < len; i++) {&nbsp; &nbsp; ret.push(arr[i%arr.length]);&nbsp; }&nbsp; return ret;}repeatArr('abcde'.split(''), 10);//["a", "b", "c", "d", "e", "a", "b", "c", "d", "e", "a", "b", "c", "d"]function repeatArr(arr, repeats) {&nbsp; var ret = [];&nbsp; for (var i = 0; i < repeats.length; i++) {&nbsp; &nbsp; for (var j = repeats[i][0]; j < repeats[i][1]; j++) {&nbsp; &nbsp; &nbsp; ret.push(arr[j % arr.length]);&nbsp; &nbsp; }&nbsp; }&nbsp; return ret;}repeatArr('abcde'.split(''), [[0, 5], [0, 3], [0, 3]]);//["a", "b", "c", "d", "e", "a", "b", "c", "a", "b", "c"]

慕码人8056858

Array( 10000 ).fill( 0 ).map( o => String.fromCharCode( Math.floor( Math.random() * 26 ) + 97 ) )
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript