I'd like to know how to make the values of an object become numbers. I read about Methods valueOf()
, and toString()
, but I have not figured out how to use them to that end, my attempts have not worked much. Thank you in advance.
I'd like to know how to make the values of an object become numbers. I read about Methods valueOf()
, and toString()
, but I have not figured out how to use them to that end, my attempts have not worked much. Thank you in advance.
You can use the methods parseInt(<string>)
and parseFloat(<string>)
.
You can see the use of these functions here . But in essence what they do is to transform a string into a number, changing the string type to int (in the case of parseInt
) or to floating point (in the case of parseFloat
).
// Objeto original:
var oSrc = {
"name": "testy McTestFace",
"age": "21",
"canDrink": "1",
"canDrive": "false"
}
//Conversão de propriedades
for (p in oSrc) { // Para cada propriedade,
oSrc[p] = parseInt(oSrc[p]) // Armazene o valor convertido para inteiro
|| oSrc[p]; // ou mantenha o valor atual.
}
console.log(oSrc);
Result:
{
"name": "testy McTestFace",
"age": 21, // Valor convertido
"canDrink": 1, // Valor convertido
"canDrive": "false"
}
Without knowing the context you are trying to use, the question is a little broad, but, as you mentioned, it is possible in some objects to call the methods .valueOf()
or .toString()
and with utility.
These methods make a Type, object-to-string, or object-to-number conversion, sometimes "crude", with semantic meaning.
A good example is a Date object, where you can use .toString()
to convert to text, and .valueOf()
to convert to a number, the timestamp.
var data = new Date();
data.toString(); // "Fri Jun 03 2016 22:27:57 GMT+0100 (WEST)"
data.valueOf(); // 1464989277351
Hello, your question is really out of context, but I think I understand what point you want to reach.
The .toString()
and .valueOf()
methods are special functions that are implicitly called when you use some specific expressions, such as direct conversion to String or Number.
As you want to know how to use them, then we will have to deal with the construction of the object in question.
Example using .toString()
:
// construtor da "classe" Pessoa
function Pessoa(nome){
this.nome = nome;
this.toString = function(){
return this.nome;
};
}
var eu = new Pessoa('William');
console.log('Olá, meu nome é '+eu);
// Imprime "Olá, meu nome é William"
console.log(String(eu));
// Imprime "William"
In the case of the .valueOf()
method, it explicitly references the value you set, as your own example, a number:
// construtor de um número "especial"
function NumeroEspecial(num){
this.num = num;
this.valueOf = function(){
return this.num;
};
}
var num = new NumeroEspecial(5);
console.log(num + 1);
// Imprime 6
console.log(Number(num));
// Imprime 5
This is an explanation just for you to know the initial process, there are other factors to consider before using these types of special methods.
Well, I hope I have helped!