大家好。我应该完成这项简短的任务。它分为两个部分。我已经完成了第一部分(尽我所能,但我愿意采取更好的方法),而第二部分则给我带来了问题。任务如下所示:
首先创建一个具有以下值的名为data的对象数组:
注意:每个对象都应以“主要”和“时间”作为键。编写一个名为“ interestCalculator”的函数,该函数将数组作为单个参数并执行以下操作:
根据条件确定适用的费率:
使用公式计算每个对象的兴趣:
(principal * rate * time) / 100.
该函数应该返回一个称为interestData
的对象数组,每个单独的对象都应以键“ principal”,“ rate”,“ time”和“ interest”作为键及其相应的值。在返回语句之前记录'interestData'数组以进行控制台。最后,调用/执行该函数并传递您创建的“数据”数组。*
如何使用键从函数中返回对象?
这是我已经尝试过的
const objArr = [{
"principal": 2500,
"time": 1.8
},
{
"principal": 1000,
"time": 5
},
{
"principal": 3000,
"time": 1
},
{
"principal": 2000,
"time": 3
}
]
//console.log(objArr.length)
function interestCalculator(array) {
let rate = 0;
let interestData = [];
array.forEach(function(entry) {
if (entry.principal >= 2500) {
if (entry.time > 1.5 && entry.time < 3) {
rate = 3;
} else if (entry.time >= 3) {
rate = 4;
}
} else if (entry.principal < 2500 || entry.time <= 1) {
rate = 2;
} else {
rate = 1;
}
const interest = (entry.principal * rate * entry.time) / 100;
interestData.push(entry.principal, rate, entry.time, interest);
//return interest;
})
console.log(interestData.length);
}
interestCalculator(objArr);
提前感谢。
要构建对象,请使用符号{key: value, key2: value2, ...}
interestData.push(
{
"principal": entry.principal,
"rate": rate,
"time": entry.time,
"interest": interest
}
);
const objArr = [{"principal": 2500, "time": 1.8},
{"principal": 1000, "time": 5},
{"principal": 3000, "time": 1},
{"principal": 2000, "time": 3}]
function interestCalculator(array) {
let rate = 0;
let interestData = [];
array.forEach(function(entry) {
if (entry.principal >= 2500) {
if (entry.time > 1.5 && entry.time < 3) {
rate = 3;
} else if (entry.time >= 3) {
rate = 4;
}
} else if (entry.principal < 2500 || entry.time <= 1) {
rate = 2;
} else {
rate = 1;
}
const interest = (entry.principal * rate * entry.time) / 100;
interestData.push({
"principal": entry.principal,
"rate": rate,
"time": entry.time,
"interest": interest
});
})
console.log(interestData);
}
interestCalculator(objArr);