สมมติว่ามีอาร์เรย์อ็อบเจ็กต์:
var employee = [
{ name: "John", amount: 800 },
{ name: "David", amount: 500 },
{ name: "Bob", amount: 450 }
];ต้องการคูณ amount ด้วย 2 กรณีที่มากกว่า 500 ผลลัพธ์ที่คาดหวัง:
[
{ name: 'John', amount: 1600 },
{ name: 'David', amount: 500 },
{ name: 'Bob', amount: 900 }
]ตัวอย่างโค้ด
var employee = [
{ name: "John", amount: 800 },
{ name: "David", amount: 500 },
{ name: "Bob", amount: 450 }
];
console.log("Before multiplying the result=");
console.log(employee);
for (var index = 0; index < employee.length; index++) {
if (employee[index].amount > 500) {
employee[index].amount = employee[index].amount * 2;
}
}
console.log("After multiplying the result=");
console.log(employee);รันด้วยคำสั่ง:
node fileName.js
ชื่อไฟล์: demo257.js
ผลลัพธ์
PS C:\Users\Amit\javascript-code> node demo257.js
Before multiplying the result=
[ { name: 'John', amount: 800 }, { name: 'David', amount: 500 }, { name: 'Bob', amount: 450 } ]
After multiplying the result=
[ { name: 'John', amount: 1600 }, { name: 'David', amount: 500 }, { name: 'Bob', amount: 900 } ]แนวทางทันสมัย: ใช้ forEach() หรือ map() จะอ่านง่ายกว่า เช่น employee.forEach(e => { if (e.amount > 500) e.amount *= 2; });