Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
How to convert a numeric property of an object in a class to a number and add with other numbers in JS?

I want to add 2 values together at the method in the customer class. one of them is a number and the other is an object property stored in a new class, the send method(a-b) works well, but the receive method(a+b) doesn't work as a number because it's an object and it is like a string in js, what is the solution?

export class Customer {
  constructor(name, password, balance) {
    {
      this.name = name;
      this.password = password;
      this.balance = balance;
    }

    this.send = function (amount) {
      return (this.balance -= amount);
    };
    this.receive = function (amount) {
      return (this.balance += amount);
    };
  }
}

export let student = new Customer("alex", "alex", 200);
export let victim1 = new Customer("tom", "cat", 1000);
export let victim2 = new Customer("jerry", "mous", 500);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use unary plus operator to convert amount to number before use it

class Customer {
  constructor(name, password, balance) {
    {
      this.name = name;
      this.password = password;
      this.balance = balance;
    }

    this.send = function (amount) {
      return (this.balance -= +amount); // magic here
    };
    this.receive = function (amount) {
      return (this.balance += +amount); // and here
    };
  }
}

let student = new Customer("alex", "alex", 200);
let victim1 = new Customer("tom", "cat", 1000);

student.send(victim1.balance);
console.log(student.balance)
student.receive(victim1.balance);
console.log(student.balance)

student.send("500");
console.log(student.balance)
student.receive("100");
console.log(student.balance)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda