如何编写将数组内的对象作为输出返回的Javascript函数

问题描述 投票:0回答:1

大家好。我应该完成这项简短的任务。它分为两个部分。我已经完成了第一部分(尽我所能,但我愿意采取更好的方法),而第二部分则给我带来了问题。任务如下所示:

  • 首先创建一个具有以下值的名为data的对象数组:

    1. Principal-2500,time- 1.8
    2. Principal-1000,time- 5
    3. Principal- 3000,time- 1
    4. Principal- 2000,time- 3

注意:每个对象都应以“主要”和“时间”作为键。编写一个名为“ interestCalculator”的函数,该函数将数组作为单个参数并执行以下操作:

根据条件确定适用的费率:

  • 如果主体大于或等于2500并且时间大于1且小于3,则比率= 3
  • 如果本金大于或等于2500并且时间大于或等于3,则比率= 4
  • 如果本金小于2500或时间小于或等于1,则比率= 2
  • 否则,费率= 1;

使用公式计算每个对象的兴趣:

(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);

提前感谢。

javascript arrays loops object push
1个回答
0
投票

要构建对象,请使用符号{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);
© www.soinside.com 2019 - 2024. All rights reserved.