Variable de valeur d'objet Javascript [dupliquer]
Nov 20 2020
Je veux faire un calcul dans un objet js. Est-ce possible?
foo: [
{
value: 1000
target:50
process: (target*value)/100
},
{
value: 500
target:100
process: (target*value)/100
}]
La process
clé doit être calculée à partir de value
et target
. Y a-t-il un moyen d'y parvenir? Js
Réponses
1 elclanrs Nov 20 2020 at 02:56
Vous pouvez créer process
un getter:
const foo = [
{
value: 1000,
target: 50,
get process() {
return (this.target * this.value) / 100;
}
},
{
value: 500,
target: 100,
get process() {
return (this.target * this.value) / 100;
}
}
];
Et puis utilisez l'accès à la propriété:
console.log(foo[0].process); //=> 500
console.log(foo[1].process); //=> 500
IsraGab Nov 20 2020 at 02:58
Le processus doit être une fonction ou un accesseur:
var foo= [
{
value: 1000,
target:50,
process() { return (this.target*this.value)/100}
},
{
value: 500,
target:100,
process() { return (this.target*this.value)/100}
}]
// use it like this:
console.log(foo[0].process()); //=> 500
console.log(foo[1].process()); //=> 500