javascript - 将名称和金额推送到 javascript 对象
问题描述
我正在尝试为网站创建一个应用程序,用户可以向该网站上的人汇款。有点像抽搐。所以我想创建一个顶级列表,但我不熟悉使用对象,所以我遇到了一些麻烦并以更简单的方式解释我的问题我在我的代码中添加了注释
var myvar = [];
cb.onTip(function(tip){
// If username already exists in myvar then i want to just increase the amount for this user else if username does not exist i want to push up the name and amount to myvar
myvar.push({name: tip.from_user, amount: tip.amount});
});
function sendtoplist(user) {
var msg;
for(var i = 0; i <= 3; i++) {
// Here i am trying to create a toplist but i want to sort it by the amount. How can i do this?
msg += myvar.name + ' ' + myvar.amount+'\n';
}
// For some reason this sendNotice returns undefined (probably because i have no idea how to work with objects)
cb.sendNotice(msg, '', '#000000', '#FFFFFF', 'bold');
cb.setTimeout(sendtoplist, 30000);
}
cb.setTimeout(sendtoplist, 30000);
解决方案
您知道哪个特定功能不起作用吗?如果是这样,它会向您显示哪个错误?
到你的第一个功能:
//myvar should be already as an array, imported from a database for example
cb.onTip(function(tip){
// If username already exists in myvar then i want to just increase the amount for this user else if username does not exist i want to push up the name and amount to myvar
var personName = {};
personName.name = tip.from_user;
personName.amount = tip.amount;
var userExist = false;
for (let i=0; i < myvar.length; i++) {
if (myvar[i].name == personName.name){
myvar[i].amount += personName.amount;
userExist = true;
break;
}
}
if (!userExist) {
myvar.push(personName);
}
});
你清楚吗?如果不让我知道。
对于您的第二个功能,学习一些 AngularJS 基础知识,这非常简单,您可以使用过滤器以及您需要的过滤器(“orderBy”)
注意:我真的建议你学习一个框架,而不是使用普通的 JS。如果你不想学那么多,就学AngularJS,它一定很容易学。但是如果你认为你想学习一些现代框架,学习 Angular(需要使用 typescript)
推荐阅读
- javascript - 如何使用 JS 将一个元素的 ID 移动到另一个元素
- r - 如何处理循环中的多个数据集以使用阈值执行二进制分类?
- ruby - macOS Big Sur 中的 Ruby 安装 (2.2.2) 失败
- sql - 如何在大查询中删除版本较低的记录?
- java - Gradle 在 Micronaut 项目中添加模块依赖
- ruby-on-rails - Rails 和现有的 Postgres 数据库
- angular - Angular 服务 - 为什么行为主题而不是使用变量?
- apache-kafka - 如何关闭正在运行的 Confluent Cloud 集群?
- rest - Gmail 的 Method: users.labels.patch 允许您做什么,这与 users.labels.update 有何不同?
- ios - 尝试在 Swift 代码中通过 AppleScript 运行 shell 脚本时出现与引号相关的错误