javascript - 返回一个包含 N 个元素的新数组的简洁方法,其中填充了另一个数组中的迭代值?普通 JavaScript

标签 javascript arrays

我有一个给定的数组,其元素数量不确定,该数组可以是数字或字符串,然后我需要生成一个由第一个数组的迭代元素组成的 N 个元素的新数组

我已经有一个函数可以做到这一点,但它仅在原始数组是连续数字时才有效,不适用于字符串。关于如何实现它,我有无数的想法。我可以将数组连接到一个新数组,直到它等于或大于所需的元素数量,然后将新数组的长度设置为所需的数量,但是有没有更简洁、优雅的方法来做到这一点?

想法 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))

想法 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,猫,羊,狗,猫,羊,狗,猫,羊,狗,猫,羊,狗]

最佳答案

您可以稍微调整您的第二个想法 - 计算需要重复初始数组的次数以得出所需的总项目数,然后将其展平并.slice:

let array = [1,2,3];
let length = 13;
const fromLength = Math.ceil(length / array.length);
let result = Array.from( { length: fromLength }, () => array )
  .flat()
  .slice(0, length);

console.log(result);

关于javascript - 返回一个包含 N 个元素的新数组的简洁方法,其中填充了另一个数组中的迭代值?普通 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59529059/

相关文章:

javascript - JQuery ajax中基本授权的使用

java - 模仿Java的ArrayList.remove(o)的函数

javascript - Chrome DevTools,内存 : what is `feedback_cell` and how to resolve memory leak that traces to it?

javascript - 在react-router-dom中如何像react-navigation一样获得 `previous`?

c - C语言中如何返回一个数组?

c - C中字符串数组的数组

javascript - 如何使用 Yeoman 缩小 Bower 组件?

php - 将php数组插入RDS

arrays - Julia 语言 : How to create an array of structs inside a for loop

javascript - <node.js> 如何有效地将平面值数组解析为具有嵌套属性的对象?