ตัวแปรค่าวัตถุ Javascript [ซ้ำ]
Nov 20 2020
ฉันต้องการทำการคำนวณภายใน js-object เป็นไปได้หรือไม่
foo: [
{
value: 1000
target:50
process: (target*value)/100
},
{
value: 500
target:100
process: (target*value)/100
}]
processที่สำคัญควรจะคำนวณจากและvalue targetมีวิธีนี้ไหม js
คำตอบ
1 elclanrs Nov 20 2020 at 02:56
คุณสามารถสร้างprocessgetter:
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;
}
}
];
จากนั้นใช้การเข้าถึงคุณสมบัติ:
console.log(foo[0].process); //=> 500
console.log(foo[1].process); //=> 500
IsraGab Nov 20 2020 at 02:58
กระบวนการควรเป็นฟังก์ชันหรือตัวเข้าถึง:
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