[英]Create array and randomize node.js array
I'm trying to write a cisco webex
bot which get all people in the space(room) and randomly write only one name.我正在尝试编写一个
cisco webex
机器人,它可以让所有人进入空间(房间)并随机只写一个名字。 I have this code我有这个代码
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!');
});
});
But this doesn't work.但这不起作用。 Also name after i use
let arrays = names.split('\n');
在我使用之后命名为
let arrays = names.split('\n');
separated by space and don't have comma.用空格隔开,没有逗号。 I think because of what code doesn't work Output of console log:
我认为由于控制台日志的哪些代码不起作用 Output :
[ 'George Washington' ] [ '乔治华盛顿' ]
[ 'John' ] [ '约翰' ]
[ 'William Howard Taft' ] ['威廉霍华德塔夫脱']
Main question now how to turn output to array?现在的主要问题是如何将 output 转换为数组?
That's because arrays[Math.floor(Math.random()*items.length)] only assigns an array with length 3. You need to randomise the index and push to array or use a sort function on the original array这是因为 arrays[Math.floor(Math.random()*items.length)] 只分配长度为 3 的数组。您需要随机化索引并推送到数组或在原始数组上使用排序 function
var array = arrays.sort((a,b)=>{
return Math.floor(Math.random()*arrays.length);
});
Here is how to get a single name from your data, and ensuring it is a string.以下是如何从您的数据中获取单个名称,并确保它是一个字符串。 There are only four names in the array, so run the snippet several times if you keep getting the same name.
数组中只有四个名称,因此如果您始终获得相同的名称,请多次运行该代码段。
// 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)
A tip: don't name your array "array" or "arrays" - it is not meaningful.提示:不要将您的数组命名为“array”或“arrays”——这没有意义。 Use good naming conventions and meaningful variable names that help others understand what the code is doing.
使用良好的命名约定和有意义的变量名,以帮助其他人理解代码在做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.