我正在尝试制作一个从数组中选取一个随机字符串的javascript,并且它会这样做,但在输出后它总是说“unidentified”。这不会是一个大问题,除了我试图这样做10-20次这一事实,这使得10-20“身份不明的人”在尝试阅读字符串的过程中受到阻碍。
//Draw random contestants for a game show!
var contestants = ["Alejandro", "Amy", "AnnMaria", "B", "Beardo", "Beth", "Blainley", "Brick", "Bridgette", "Cameron", "Cody", "Courtney", "Dakota", "Dave", "Dawn", "DJ", "Duncan", "Ella", "Eva", "Ezekiel", "Geoff", "Gwen", "Harold", "Heather", "Izzy", "Jasmine", "Jo", "Justin", "Katie", "Leonard", "Leshawna", "Lightning", "Lindsey", "Max", "Mike", "Noah", "Owen", "Rodney", "Sadie", "Sam", "Samey", "Scarlett", "Scott", "Shawn", "Sierra", "Sky", "Staci", "Sugar", "Tofur", "Trent", "Tyler", "Zoey"];
var randomContestant = function () {
console.log(contestants[Math.floor(Math.random() * 52)]);
};
//randomContestant(); to pick a random contestant.
var drawContestants = function (howMany) {
for (var i = 0 ; i < howMany; i++) {
console.log (randomContestant(i + howMany));
}
};
//drawContestants(numberOfContestantsYouWantDrawn); to draw a number of random contestants.
从我看到的其他问题来看,它与函数的参数是空白的事实有关吗?如果这是问题,我应该把它放在那里让它在输出后停止给出“Unidentified”?
(我现在只做了几天的javascript,所以如果这个问题得到了解答,我要么错过了那个问题,要么因为它更先进而无法理解它们的答案。)
答案 0 :(得分:2)
您需要var files = [];
Liferay.Service(
'/group/get-user-sites-groups',
function(obj) {
var result;
for(var i= 0; i< obj.length; i++)
{
result = obj[i].groupId;
Liferay.Service(
'/dlfolder/get-subfolder-ids',
{
groupId: result,
folderId: 0,
recurse: true
},
function(subIds)
{
var folders = subIds;
folders.unshift(0);
for(var i=0; i< folders.length; i++)
{
Liferay.Service(
'/dlapp/get-file-entries',
{
repositoryId: result,
folderId: folders.pop()
},
function(object) {
if(object.length > 0)
{
files=files.concat(object);
}
});
}
});
}
});
该值。您只打印出该值。
return
答案 1 :(得分:1)
JavaScript函数默认返回undefined。
您可以尝试重构代码,以便将循环控制日志52次,而不是调用控制台记录52次的函数。
答案 2 :(得分:1)
您已将参数传递给randomContestant
,但您未在该功能中使用该参数。您也不会因为他们被选中而移除参赛者。尝试这样的事情:
const contestants = ["Alejandro", "Amy", "AnnMaria", "B", "Beardo", "Beth", "Blainley", "Brick", "Bridgette", "Cameron", "Cody", "Courtney", "Dakota", "Dave", "Dawn", "DJ", "Duncan", "Ella", "Eva", "Ezekiel", "Geoff", "Gwen", "Harold", "Heather", "Izzy", "Jasmine", "Jo", "Justin", "Katie", "Leonard", "Leshawna", "Lightning", "Lindsey", "Max", "Mike", "Noah", "Owen", "Rodney", "Sadie", "Sam", "Samey", "Scarlett", "Scott", "Shawn", "Sierra", "Sky", "Staci", "Sugar", "Tofur", "Trent", "Tyler", "Zoey"];
const randomContestant = function (pool) {
return pool[Math.floor(Math.random() * pool.length)];
};
const drawContestants = function (howMany) {
// make a copy so as not to mutate the original array
let contestantPool = contestants.slice();
for (let i = 0 ; i < howMany; i++) {
const pick = randomContestant(contestantPool);
console.log(pick);
const index = contestantPool.indexOf(pick);
contestantPool =
[...contestantPool.slice(0, index),
...contestantPool.slice(index + 1),
];
}
};
drawContestants(10);
&#13;