[英]Create array and randomize node.js array
我正在嘗試編寫一個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');
用空格隔開,沒有逗號。 我認為由於控制台日志的哪些代碼不起作用 Output :
[ '喬治華盛頓' ]
[ '約翰' ]
['威廉霍華德塔夫脫']
現在的主要問題是如何將 output 轉換為數組?
這是因為 arrays[Math.floor(Math.random()*items.length)] 只分配長度為 3 的數組。您需要隨機化索引並推送到數組或在原始數組上使用排序 function
var array = arrays.sort((a,b)=>{
return Math.floor(Math.random()*arrays.length);
});
以下是如何從您的數據中獲取單個名稱,並確保它是一個字符串。 數組中只有四個名稱,因此如果您始終獲得相同的名稱,請多次運行該代碼段。
// 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”或“arrays”——這沒有意義。 使用良好的命名約定和有意義的變量名,以幫助其他人理解代碼在做什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.