javascript - 如何从对象数组中读取特定值并将所有值添加到一个变量中?
问题描述
关于我的数组:
var list = []
function arrObject(name, coins, id) {
this.name = name
this.coins = coins
this.id = id
this.listed = function(){
return (this.name + "" +"["+this.coins+"]")
}
}
list.push(new arrObject(user.username, coinsamount, user.id))
添加两个用户后,我的 console.log 输出如下所示:
[
{
name: 'Mango',
coins: '19',
id: '454214634158999514',
listed: [Function (anonymous)]
}
]
[
{
name: 'Goodmg',
coins: '41',
id: '721805465937021781',
listed: [Function (anonymous)]
}
]
如何获取“硬币”值并将它们加到一个变量中?
EDIT.1 将功能从 更改Object
为arrObject
EDIT.2
const Discord = require('discord.js')
const embeds = require('./../../embeds.js')
var running = 0
module.exports = {
commands: 'rjoin',
minArgs: 1,
maxArgs: 2,
expectedArgs: '**coins amount**',
callback: (message, arguments) => {
function calcCoinSum(list) {
return list.reduce((prev, curr) => {
return prev + Number.parseInt(curr.coins);
}, 0);
}
const channelmessage = message.client.channels.cache.get('802537184824524820')
const coinsamount = arguments[0]
function wait(miliseconds){
return new Promise(resolve => setTimeout(resolve, miliseconds))
}
//channelmessage.send(value.name + `: **${value.coins}** coins`)
async function loop(){
while(true){
await wait(5000)
if(running === 2){
console.log(calcCoinSum(list))
break
}
}
}
function arrObject(name, coins, id) {
this.name = name
this.coins = coins
this.id = id
this.listed = function(){
return (this.name + "" +"["+this.coins+"]")
}
}
const list = []
if(message.channel.id === '802611173118705684'){
loop()
var user = message.author
if(running === 0){
console.log('Roll Started!')
channelmessage.send('Roluette has started! Type ?rjoin (coins amount) to join!')
list.push(new arrObject(user.username, coinsamount, user.id))
running = 1
setTimeout(() => {
running = 2
console.log('Roll ended')
}, 15000);
return
}
if(running === 1){
list.push(new arrObject(user.username, coinsamount, user.id))
}
}
}
}
解决方案
使用reduce这应该相当简单:
function calcCoinSum(list) {
return list.reduce((prev, curr) => {
return prev + Number.parseInt(curr.coins);
}, 0);
}
function arrObject(name, coins, id) {
this.name = name
this.coins = coins
this.id = id
this.listed = function () {
return (this.name + "" + "[" + this.coins + "]")
}
}
const list = [];
list.push(new arrObject('Mango', '19', '454214634158999514'));
list.push(new arrObject('Goodmg', '41', '721805465937021781'));
console.log('The coins sum is:', calcCoinSum(list))
推荐阅读
- javascript - getAddress.io API 脚本
- javascript - 如何显示所有被禁止用户的禁止列表?
- reactjs - 在draftjs中渲染“@ with random text”时崩溃
- python - 尝试在 Ubuntu 上安装 osmread 模块时出错
- javascript - Angular 的 MSAL/Microsoft 授权问题:如何验证 id_token?
- angular - “ng serve”时出错无法读取未定义的属性“loadChildren”
- php - Opencart 3. 在oc_product_image中添加新字段
- javascript - 如何在 mvc 视图中生成页面链接(API 方法已经返回分页结果)
- docker - 为什么在 minikube VM 中无法访问 docker-daemon?
- powershell - 在密码即将到期时向 AD 用户发送电子邮件