[英]How to generate an array with repeated string javascript
How to generate an array with function like this? 如何生成具有这样功能的数组?
var name = ["monkey","monkey"..."horse","horse",..."dog","dog",..."cat","cat"...]
In my real case, I may have to repeat each name 100 times.. 在我的真实情况下,我可能不得不重复每个名字100次。
Assuming that you already have that words in a array try this code: 假设您已经在数组中包含这些单词,请尝试以下代码:
var words = ["monkey", "hourse", "dog", "cat"];
var repeatWords = [];
for(var i = 0; i < words.length; i++)
{
for(var j = 0; j < 100; j++)
{
repeatWords.push(words[i]);
}
}
You can try this, specifying the words to be used, and the times to create the array you need. 您可以尝试此操作,指定要使用的单词以及创建所需数组的时间。
var neededWords = ["Cat", "Hourse", "Dog"];
var finalArray = [];
var times = 10;
for (var i = 0; i < neededWords.length; i++) {
for (var n = 0; n < times; n++) {
finalArray.push(neededWords[i]);
}
}
console.log(finalArray);
Hope that helps! 希望有帮助!
If I understood correctly you need a function that takes as an argument a collection of items and returns a collection of those items repeated. 如果我正确理解,则需要一个函数,该函数将项目的集合作为参数并返回重复的那些项目的集合。 From your problem statement, I assumed that the repetition has to be adjusted by you per collection item - correct me if I am wrong.
根据您的问题陈述,我认为您必须针对每个收款项目调整重复次数-如果我错了,请纠正我。
The function I wrote does just that; 我写的函数就是这样做的。 it takes an object literal
{name1:frequency1,name2:frequency2..}
which then iterates over the keys and pushes each one as many times as indicated by the associated frequency in the frequencyMap object. 它采用对象文字
{name1:frequency1,name2:frequency2..}
,然后迭代键并按频图对象中相关频率指示的次数按一次。
function getRepeatedNames( frequencyMap ) {
var namesCollection = [];
Object.keys(frequencyMap).forEach(function(name,i,names){
var freq = frequencyMap[name];
freq = (isFinite(freq)) ? Math.abs(Math.floor(freq)) : 1;
for (var nameCounter=0; nameCounter<freq; nameCounter++) {
namesCollection.push(name);
}
});
return namesCollection;
}
Non-numeric values in the frequency map are ignored and replaced with 1. 频率图中的非数字值将被忽略并替换为1。
Usage example: If we want to create an array with 5 cats and 3 dogs we need to invoke 用法示例:如果我们要创建一个包含5只猫和3只狗的数组,则需要调用
getRepeatedNames({cat: 2, dog: 3}); // ["cat","cat","dog","dog","dog"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.