首页 > 解决方案 > 将名称和金额推送到 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);

标签: javascriptobject

解决方案


您知道哪个特定功能不起作用吗?如果是这样,它会向您显示哪个错误?

到你的第一个功能:

//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)


推荐阅读