我有一个给定的数组,其中元素的数量不确定,该数组可以是数字或字符串,然后我需要根据第一个数组的迭代元素生成一个由N个元素组成的新数组
我已经有一个函数可以执行此操作,但是它仅在原始数组为连续数字时才有效,而不适用于字符串。关于如何实现这一点,我有无数的想法。我可以将数组连接到一个新数组,直到其等于或大于所需的元素数量,然后将新的数组长度设置为所需的数量,但是有没有更简洁,更优雅的方法呢?
IDEA 01 Codepen
function populateArray(qty) {
// Array to populate from
let array = [1,2,3];
//Determine the Range Length of the array and assign it to a variable
let min = array[0];
let max = array[array.length - 1];
const rangeLength = (max - min + 1);
//Initialize uniqueArray which will contain the concatenated array
let uniqueArray = [];
//Test if quantity is greater than the range length and if it is,
//concatenate the array to itself until the new array has equal number of elements or greater
if (qty > rangeLength) {
//Create an array from the expansion of the range
let rangeExpanded = Array.from(new Array(rangeLength), (x,i) => i + min);
while (uniqueArray.length < qty) {
uniqueArray = uniqueArray.concat(rangeExpanded);
}
}
// Remove additional elements
uniqueArray.length = qty
return uniqueArray;
}
console.log(populateArray(13))
IDEA 02 codepen,但它将整个原始数组(而非迭代项)填充到新数组中13次
// FILL A NEW ARRAY WITH N ELEMENTS FROM ANOTHER ARRAY
let array = [1,2,3];
let length = 13;
let result = Array.from( { length }, () => array );
console.log(result);
如果原始数组由字符串组成,则预期结果为[1,2,3,1,2,3,1,2,3,1,2,3,1],预期结果为[dog,cat,sheep ,狗,猫,绵羊,狗,猫,绵羊,狗,猫,绵羊,狗]
我将使用@CertainPerformance的答案。但这是另一种方法,仅用于开箱即用的目的
// A function for getting an index up to length's size
function getIDX(idx, length){
return idx <= length ? idx : getIDX(idx-length, length);
}
const newArrayLength = 13;
const sourceArray = [1,2,3];
const resultArray = [];
for(let i=0; i< newArrayLength; i++){
resultArray[i]=sourceArray[getIDX(i+1, sourceArray.length)-1];
}
编辑1:我正在比较此方法与此处描述的其他方法的性能,似乎如果您想创建一个非常大的新数组(例如:newArrayLength = 10000),由于getIDX()
函数的大小,需要花很多时间才能完成调用堆栈。所以我getIDX()
通过删除递归来改进了功能,现在复杂度为O(1):
function getIDX(idx, length){
if (length === 1) {return idx};
const magicNumber = length * (Math.ceil(idx/length)-1);
return idx - magicNumber;
}
有了新getIDX()
功能,这种方法似乎是性能最高的。您可以在这里查看测试:https : //jsbench.me/v7k4sjrsuw/1
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句