JavaScript 在一个对象中只乘以特定的值
比方说,以下是我们的对象 –
var employee =
[
{ name: "John", amount: 800 },
{ name: "David", amount: 500 },
{ name: "Bob", amount: 450 }
]
我们需要将 “金额 “值乘以2,只有当金额大于500时,即预期输出应该是 −
[
{ name:'John',amount:16001600 },
{ 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 }
]