我正在尝试写一个cisco webex机器人,它可以让所有的人都在这个空间(房间)里,并且随机地只写一个名字。我有这个代码
framework.hears("daily host", function (bot) {
console.log("Choosing a daily host");
responded = true;
// Use the webex SDK to get the list of users in this space
bot.webex.memberships.list({roomId: bot.room.id})
.then((memberships) => {
for (const member of memberships.items) {
if (member.personId === bot.person.id) {
// Skip myself!
continue;
}
let names = (member.personDisplayName) ? member.personDisplayName : member.personEmail;
let arrays = names.split('\n');
var array = arrays[Math.floor(Math.random()*items.length)];
console.log(array)
bot.say(`Hello ${array}`);
}
})
.catch((e) => {
console.error(`Call to sdk.memberships.get() failed: ${e.messages}`);
bot.say('Hello everybody!');
});
});但这不管用。也可以在我使用let arrays = names.split('\n');后命名,用空格分隔,没有逗号。我认为是因为什么代码不能工作,控制台日志的输出:
“乔治·华盛顿”
“约翰”
“威廉·霍华德·塔夫脱”
现在的主要问题是如何将输出转换为数组?
发布于 2021-11-23 15:12:17
这是因为arraysMath.floor(Math.random()*items.length)只分配长度为3的数组。您需要将索引随机化并推入数组,或者对原始数组使用排序函数
var array = arrays.sort((a,b)=>{
return Math.floor(Math.random()*arrays.length);
});如果您希望根据您的问题获得输出,则可以使用reduce而不是sort。
var arrays = [ 'George Washington', 'John', 'William Howard Taft'];
var array = arrays.reduce((a,i)=>{
if(!a) a = [];
a.splice(Math.floor(Math.random()*arrays.length), 0, [i]);
return a;
},[]);发布于 2021-11-25 07:51:38
下面是如何从您的数据中获取单个名称,并确保它是一个字符串。该数组中只有四个名称,因此如果您一直获得相同的名称,请多次运行代码片段。
// A list of names. Notice that Arraymond is an array; the other names are strings.
const names = [ 'George Washington', 'John', 'William Howard Taft', ['Arraymond'] ];
// Randomize the names
const randomNames = names.sort(() => Math.random() - 0.5);
// Get the first name. Make sure the name is a string (not an array)
const name = randomNames[0].toString();
console.log(name)
提示:不要将数组命名为" array“或”array“--这是没有意义的。使用良好的命名约定和有意义的变量名来帮助其他人理解代码的作用。
https://stackoverflow.com/questions/70082498
复制相似问题